I've been using the module azure-sdk-for-go/sdk/messaging/azservicebus v0.3.1 to connect my consumer with Azure Service Bus but the code implemented only receive a fixed number of message and then stop the application and I'would like to keep the consumer listening the queue. Follow my code:
client, err := azservicebus.NewClientFromConnectionString("Connection String", nil)
if err != nil {
log.Fatalf("Failed to create Service Bus Client: %s", err.Error())
}
receiver, err := client.NewReceiverForQueue("queue", nil)
if err != nil {
log.Fatalf("Failed to create Consumer: %s", err.Error())
}
messages, err := receiver.ReceiveMessages(context.TODO(), 10, nil)
if err != nil {
log.Fatalf("Failed to receive Messages: %s", err.Error())
}
for _, message := range messages {
body, err := message.Body()
if err != nil {
log.Fatalf("Failed to parse message body: %s", err.Error())
}
fmt.Println("Message --->", string(body))
err = receiver.CompleteMessage(context.TODO(), message)
if err != nil {
log.Fatalf("Failed to complete message: %s", err.Error())
}
fmt.Printf("Received and completed message\n")
}
You have 99% of the code - as you noted ReceiveMessages only returns the amount you requested.
So you just want to wrap your logic in a loop so you can run it continually:
for {
messages, err := receiver.ReceiveMessages(context.TODO(), 10, nil)
if err != nil {
log.Fatalf("Failed to receive Messages: %s", err.Error())
}
for _, message := range messages {
body, err := message.Body()
if err != nil {
log.Fatalf("Failed to parse message body: %s", err.Error())
}
fmt.Println("Message --->", string(body))
err = receiver.CompleteMessage(context.TODO(), message)
if err != nil {
log.Fatalf("Failed to complete message: %s", err.Error())
}
}
}
BTW, 0.3.2 was just released and it contains some fixes that you'll be interested in as they do affect ReceiveMessages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With