Azure / azure-sdk-for-go

This repository is for active development of the Azure SDK for Go. For consumers of the SDK we recommend visiting our public developer docs at:
https://docs.microsoft.com/azure/developer/go/
MIT License
1.62k stars 826 forks source link

Service Bus consumer with channel #22515

Closed Tomelin closed 7 months ago

Tomelin commented 7 months ago

Feature Request

I didn't not found how work the azure-sdk-for-go with golang channel.

I create my consume func this format:

func (mq *MessageQueue) Consume(out chan<- *MessageReceiver) error {
    receiver, err := mq.Client.NewReceiverForSubscription(mq.Topic, mq.Subscription, nil)
    if err != nil {
        return err
    }
    mq.Receiver= receiver
    msgs, err := receiver.ReceiveMessages(ctx, 1, nil)
    if err != nil {
        return err
    }

    for _, msg := range msgs {
        mq.Message = msg
        out <- &mq.Receiver
    }

    return nil
}

But I undestood that *azservicebus.Receiver does not update my variable when there is a new message, it is a correct? What is the correct format for work azservicebus and channels?

richardpark-msft commented 7 months ago

We don't provide a specific channel-based version, as you've seen, so implementing this would be something you'd need to do in your own application. What you have there will do a receive of one message and push it to the channel, but I think what you're looking for is a continual "receive forever" type of style.

That gets a little more complicated since you need to use a goroutine, but it'd be something like this:

func (mq *MessageQueue) StartConsumption(out chan<- *MessageReceiver) error {
    receiver, err := mq.Client.NewReceiverForSubscription(mq.Topic, mq.Subscription, nil)
    if err != nil {
        return err
    }
    mq.Receiver= receiver

    // "run this in the background" forever.
    // TODO: You'll also need some code to handle error propagation (ie, 'ReceiveMessages' fails)
    go func() {
        // TODO: You'll need to provide some form of "stop receiving" signal. This loop obviously
        // runs forever.
        for {
            msgs, err := receiver.ReceiveMessages(ctx, 1, nil)
            if err != nil {
                return err
            }

            for _, msg := range msgs {
                mq.Message = msg
                out <- &mq.Receiver
            }
        }
    }()

    return nil
}

I'm going to close this issue as this isn't strictly a Go SDK issue but if you have other questions feel free to ask.