Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep my consumer listening the messages on Azure Sevice Bus using Azure sdk for Golang v0.3.1?

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")

    }

like image 490
Rafael Reis Avatar asked Dec 05 '25 09:12

Rafael Reis


1 Answers

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.

like image 113
Richard Park Avatar answered Dec 07 '25 05:12

Richard Park



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!