Best Venom code snippet using mqtt.persistMessages
mqtt.go
Source:mqtt.go
...84 if err != nil {85 result.Err = err.Error()86 }87 case "persistent_queue":88 err = e.persistMessages(ctx)89 if err != nil {90 result.Err = err.Error()91 }92 case "subscriber":93 result.Messages, result.MessagesJSON, result.Topics, err = e.consumeMessages(ctx)94 if err != nil {95 result.Err = err.Error()96 }97 default:98 return nil, fmt.Errorf("clientType %q must be publisher, subscriber or persistent_queue", e.ClientType)99 }100 elapsed := time.Since(start)101 result.TimeSeconds = elapsed.Seconds()102 return result, nil103}104// session prepares a client connection returning a client and a possible error105func (e Executor) session(ctx context.Context, subscriber func(client mq.Client, message mq.Message)) (mq.Client, error) {106 venom.Debug(ctx, "creating session to %v, cleanSession: %v, clientID: %v", e.Addrs, !e.PersistSubscription, e.ClientID)107 opts := mq.NewClientOptions().108 AddBroker(e.Addrs).109 SetConnectTimeout(time.Duration(e.ConnectTimeout) * time.Millisecond).110 SetCleanSession(!e.PersistSubscription).111 SetClientID(e.ClientID).112 SetProtocolVersion(mqttV311).113 SetOnConnectHandler(func(client mq.Client) {114 venom.Debug(ctx, "connection handler called. IsConnected: %v", client.IsConnected())115 })116 client := mq.NewClient(opts)117 // MQTT may send messages prior to a subscription taking place (due to pre-existing persistent session).118 // We cannot subscribe without a connection so we register a route and subscribe later119 if subscriber != nil {120 venom.Debug(ctx, "adding routes: %v", e.Topics)121 for _, topic := range e.Topics {122 client.AddRoute(topic, subscriber)123 }124 }125 token := client.Connect()126 select {127 case <-token.Done():128 if token.Error() != nil {129 venom.Debug(ctx, "connection setup failed")130 return nil, errors.Wrap(token.Error(), "failed to connect to MQTT")131 }132 // else connection complete, all good.133 case <-time.After(time.Duration(e.Timeout) * time.Millisecond):134 venom.Debug(ctx, "connection timeout")135 return nil, errors.Wrap(token.Error(), "failed to connect to MQTT")136 case <-ctx.Done():137 venom.Debug(ctx, "Context requested cancellation in session()")138 return nil, errors.New("Context requested cancellation in session()")139 }140 venom.Debug(ctx, "connection setup completed")141 return client, nil142}143// publishMessages is a step that sends configured messages to client connection144func (e Executor) publishMessages(ctx context.Context) error {145 client, err := e.session(ctx, nil)146 if err != nil {147 venom.Debug(ctx, "Failed to create session (publishMessages)")148 return err149 }150 defer client.Disconnect(disconnectTimeoutMs)151 for i, m := range e.Messages {152 if len(m.Topic) == 0 {153 return errors.Errorf("mandatory field Topic was empty in Messages[%v](%v)", i, m)154 }155 token := client.Publish(m.Topic, m.QOS, m.Retained, m.Payload)156 select {157 case <-token.Done():158 if token.Error() != nil {159 venom.Debug(ctx, "Message publish failed")160 return errors.Wrapf(token.Error(), "Message publish failed: Messages[%v](%v)", i, m)161 }162 // else publish complete, all good.163 case <-time.After(time.Duration(e.Timeout) * time.Millisecond):164 venom.Debug(ctx, "Publish attempt timed out")165 return errors.Errorf("Publish attempt timed out on topic %v", m.Topic)166 case <-ctx.Done():167 venom.Debug(ctx, "Context requested cancellation in publishMessages()")168 return errors.New("Context requested cancellation in publishMessages()")169 }170 venom.Debug(ctx, "Message[%v] %q sent (topic: %q)", i, m.Payload, m.Topic)171 }172 return nil173}174// consumeMessages is a step to consume messages from mqtt broker using client connection175func (e Executor) consumeMessages(ctx context.Context) (messages []interface{}, messagesJSON []interface{}, topics []string, err error) {176 ch := make(chan mq.Message, 1)177 defer close(ch)178 subscriber := newSubscriber(ctx, ch)179 client, err := e.session(ctx, subscriber)180 if err != nil {181 venom.Debug(ctx, "Failed to create session (consumeMessages)")182 return nil, nil, nil, err183 }184 defer client.Disconnect(disconnectTimeoutMs)185 start := time.Now()186 for _, topic := range e.Topics {187 token := client.Subscribe(topic, e.QOS, subscriber)188 select {189 case <-token.Done():190 if token.Error() != nil {191 venom.Debug(ctx, "Failed to subscribe")192 return nil, nil, nil, errors.Wrapf(token.Error(), "failed to subscribe to topic %v", topic)193 }194 // else subscription complete, all good.195 case <-time.After(time.Duration(e.Timeout) * time.Millisecond):196 venom.Debug(ctx, "Subscription attempt timed out")197 return nil, nil, nil, errors.Errorf("Subscription attempt timed out on topic %v", topic)198 case <-ctx.Done():199 venom.Debug(ctx, "Context requested cancellation")200 return nil, nil, nil, errors.New("Context requested cancellation")201 }202 }203 messages = []interface{}{}204 messagesJSON = []interface{}{}205 topics = []string{}206 venom.Debug(ctx, "message limit %d", e.MessageLimit)207 ctx2, cancel := context.WithTimeout(ctx, time.Duration(e.Timeout)*time.Millisecond)208 defer cancel()209 for i := 0; i < e.MessageLimit; i++ {210 venom.Debug(ctx, "Reading message n° %d", i)211 var t string212 var m []byte213 select {214 case msg := <-ch:215 m = msg.Payload()216 t = msg.Topic()217 case <-ctx2.Done():218 break219 }220 messages = append(messages, m)221 topics = append(topics, t)222 s := string(m)223 venom.Debug(ctx, "message received. topic: %s len(%d), %s", t, len(m), s)224 var bodyJSONArray []interface{}225 if err := venom.JSONUnmarshal(m, &bodyJSONArray); err != nil {226 bodyJSONMap := map[string]interface{}{}227 err := venom.JSONUnmarshal(m, &bodyJSONMap)228 if err != nil {229 venom.Debug(ctx, "unable to decode message as json")230 }231 messagesJSON = append(messagesJSON, bodyJSONMap)232 } else {233 messagesJSON = append(messagesJSON, bodyJSONArray)234 }235 }236 d := time.Since(start)237 venom.Debug(ctx, "read(s) took %v msec", d.Milliseconds())238 return messages, messagesJSON, topics, nil239}240// persistMessages is a step that registers or un-registers persistent topic subscriptions against a given client id241func (e Executor) persistMessages(ctx context.Context) error {242 client, err := e.session(ctx, nil)243 if err != nil {244 venom.Debug(ctx, "Failed to create session (persistMessages)")245 return err246 }247 defer client.Disconnect(disconnectTimeoutMs)248 for _, topic := range e.Topics {249 token := client.Subscribe(topic, e.QOS, func(client mq.Client, message mq.Message) {250 venom.Debug(ctx, "msg received in persist request: %v", string(message.Payload()))251 })252 select {253 case <-token.Done():254 if token.Error() != nil {255 venom.Debug(ctx, "Failed to subscribe")256 return errors.Wrapf(token.Error(), "failed to subscribe to topic %v", topic)257 }258 // else subscription complete, all good....
persistMessages
Using AI Code Generation
1import (2func main() {3 opts.SetClientID("go-simple")4 opts.SetUsername("test")5 opts.SetPassword("test")6 opts.SetCleanSession(false)7 client := mqtt.NewClient(opts)8 if token := client.Connect(); token.Wait() && token.Error() != nil {9 panic(token.Error())10 }11 client.Subscribe("test", 1, func(client mqtt.Client, msg mqtt.Message) {12 fmt.Printf("TOPIC: %s\n", msg.Topic())13 fmt.Printf("MSG: %s\n", msg.Payload())14 })15 token := client.Publish("test", 1, false, "Hello World")16 token.Wait()17 time.Sleep(3 * time.Second)18 client.Disconnect(250)19}20import (21func main() {22 opts.SetClientID("go-simple")23 opts.SetUsername("test")24 opts.SetPassword("test")25 opts.SetCleanSession(false)26 client := mqtt.NewClient(opts)27 if token := client.Connect(); token.Wait() && token.Error() != nil {28 panic(token.Error())29 }30 client.Subscribe("test", 1, func(client mqtt.Client, msg mqtt.Message) {31 fmt.Printf("TOPIC: %s\n", msg.Topic())32 fmt.Printf("MSG: %s\n", msg.Payload())33 })34 token := client.Publish("test", 1, false, "Hello World")35 token.Wait()36 time.Sleep(3 * time.Second)37 client.Disconnect(250)38}39import (40func main() {41 opts.SetClientID("go-simple")42 opts.SetUsername("test")43 opts.SetPassword("test")44 opts.SetCleanSession(false)45 client := mqtt.NewClient(opts)
persistMessages
Using AI Code Generation
1import (2func main() {3 opts.SetClientID("go-simple")4 opts.SetUsername("admin")5 opts.SetPassword("public")6 c := mqtt.NewClient(opts)7 if token := c.Connect(); token.Wait() && token.Error() != nil {8 panic(token.Error())9 }10 if token := c.Subscribe("go-mqtt/sample", 0, nil); token.Wait() && token.Error() != nil {11 fmt.Println(token.Error())12 os.Exit(1)13 }14 time.Sleep(3 * time.Second)15 if token := c.Publish("go-mqtt/sample", 0, false, "test"); token.Wait() && token.Error() != nil {16 fmt.Println(token.Error())17 os.Exit(1)18 }19 time.Sleep(3 * time.Second)20 c.Disconnect(250)21}22import (23func main() {24 opts.SetClientID("go-simple")25 opts.SetUsername("admin")26 opts.SetPassword("public")27 c := mqtt.NewClient(opts)28 if token := c.Connect(); token.Wait() && token.Error() != nil {29 panic(token.Error())30 }31 if token := c.Subscribe("go-mqtt/sample", 0, nil); token.Wait() && token.Error() != nil {32 fmt.Println(token.Error())33 os.Exit(1)34 }35 time.Sleep(3 * time.Second)36 if token := c.Publish("go-mqtt/sample", 0, false, "test"); token.Wait() && token.Error() != nil {37 fmt.Println(token.Error())38 os.Exit(1)39 }40 time.Sleep(3 * time.Second)41 c.Disconnect(250)42}
persistMessages
Using AI Code Generation
1import (2func main() {3 qMgr, err = ibmmq.Connx("QM1", nil)4 if err != nil {5 fmt.Println(err)6 }7 defer qMgr.Disc()8 mqod = ibmmq.NewMQOD()9 qObject, err = qMgr.Open(mqod, openOptions)10 if err != nil {11 fmt.Println(err)12 }13 defer qObject.Close(0)14 putmqmd = ibmmq.NewMQMD()15 putmqgmo = ibmmq.NewMQGMO()16 msgHandle, err = qObject.Put1(putmqmd, putmqgmo, []byte(msg))17 if err != nil {18 fmt.Println(err)19 }20 msg, err = qObject.Get1(putmqmd, putmqgmo, msgHandle)21 if err != nil {22 fmt.Println(err)23 }24 fmt.Println("Message received: ", msg)
persistMessages
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 mqttClient = mqtt.NewClient(mqtt.NewClientOptions())5 mqttClient.Connect()6 mqttClient.Publish("topic", 1, false, "message")7 mqttClient.Disconnect(250)8}9import (10func main() {11 fmt.Println("Hello World")12 mqttClient = mqtt.NewClient(mqtt.NewClientOptions())13 mqttClient.Connect()14 mqttClient.Publish("topic", 1, false, "message")15 mqttClient.Disconnect(250)16}17import (18func main() {19 fmt.Println("Hello World")20 mqttClient = mqtt.NewClient(mqtt.NewClientOptions())21 mqttClient.Connect()22 mqttClient.Publish("topic", 1, false, "message")23 mqttClient.Disconnect(250)24}25import (26func main() {27 fmt.Println("Hello World")28 mqttClient = mqtt.NewClient(mqtt.NewClientOptions())29 mqttClient.Connect()30 mqttClient.Publish("topic", 1, false, "message")31 mqttClient.Disconnect(250)32}33import (34func main() {35 fmt.Println("Hello World")36 mqttClient = mqtt.NewClient(mqtt.NewClientOptions())37 mqttClient.Connect()38 mqttClient.Publish("topic", 1, false, "message")39 mqttClient.Disconnect(250)40}
persistMessages
Using AI Code Generation
1import (2func main() {3 mqtt := Mqtt{}4 mqtt.Init("localhost", 1883, "test", "test", "test")5 mqtt.Connect()6 mqtt.Subscribe("topic1")7 mqtt.PersistMessages("topic1", "topic2", "test.json")8 time.Sleep(10 * time.Second)9}10import (11func main() {12 mqtt := Mqtt{}13 mqtt.Init("localhost", 1883, "test", "test", "test")14 mqtt.Connect()15 mqtt.Subscribe("topic2")16 mqtt.ReadPersistedMessages("topic2", "test.json")17 time.Sleep(10 * time.Second)18}
persistMessages
Using AI Code Generation
1import (2func main() {3 mqtt := mqtt.New()4 mqtt.SetClientId("go-client")5 mqtt.SetUsername("username")6 mqtt.SetPassword("password")7 mqtt.SetCleanSession(true)8 mqtt.SetKeepAlive(60)9 mqtt.SetWillTopic("willtopic")10 mqtt.SetWillMessage("willmessage")11 mqtt.SetWillQos(1)12 mqtt.SetWillRetained(true)13 mqtt.SetAutoReconnect(true)14 mqtt.SetReconnectInterval(5)15 mqtt.SetPersistMessages(true)16 mqtt.SetPersistDir("/home/username/")17 mqtt.SetPersistQos(1)18 mqtt.SetPersistRetained(true)19 mqtt.SetPersistMaxSize(100)20 mqtt.SetPersistMaxMessages(100)21 mqtt.SetDebug(true)22 mqtt.SetErrorChannel(make(chan error))23 mqtt.SetMessageChannel(make(chan mqtt.Message))24 mqtt.SetConnectHandler(func() {25 fmt.Println("Connected")26 })27 mqtt.SetDisconnectHandler(func() {28 fmt.Println("Disconnected")29 })30 mqtt.SetReconnectHandler(func() {31 fmt.Println("Reconnected")32 })33 mqtt.SetPublishHandler(func(msg mqtt.Message) {34 fmt.Println("Published")35 })36 mqtt.SetSubscribeHandler(func(topic string) {37 fmt.Println("Subscribed")38 })39 mqtt.SetUnsubscribeHandler(func(topic string) {40 fmt.Println("Unsubscribed")41 })42 mqtt.SetMessageHandler(func(msg mqtt.Message) {43 fmt.Println("Message received")44 })45 mqtt.Connect()46 mqtt.Publish("topic", "message", 1, true)47 mqtt.Subscribe("topic", 1)48 mqtt.Unsubscribe("topic")49 mqtt.Disconnect()50}51import (52func main() {53 mqtt := mqtt.New()54 mqtt.SetClientId("go-client")55 mqtt.SetUsername("username")56 mqtt.SetPassword("password")57 mqtt.SetCleanSession(true)58 mqtt.SetKeepAlive(60)59 mqtt.SetWillTopic("willtopic")60 mqtt.SetWillMessage("willmessage")
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!