Search code examples
azureazure-worker-rolesazureservicebusazure-servicebus-queues

Worker Role consuming a Session Partitioned Queue - MessageSessionHandler or AcceptMessageSessionAsync


I have a Service Bus Queue with several sessions, that I use as way to enforce order per entity.

And I need a worker role to read messages from this Queue, and read messages from any session, in a way that when it's reading a message from a session no other instance of this role will get messages from that session.

What would be the best way to consume those, using a MessageSessionClass or having doing the AcceptMessageSessionAsync and OnMessageAsync(messagehandler)?

Having a hard time understanding which method would fit better in a worker role.


Solution

  • The Azure SDK 2.3 introduced support for session-awareness when using OnMessageAsync. See sparse MSDN Documentation.

    The gist is that you'll implement an MessageSessionAsyncHandler to handle the messages for a given session:

    class MySessionHandler : MessageSessionAsyncHandler
    {  
        protected override async Task OnMessageAsync(MessageSession session, BrokeredMessage message)
        {
            // Do the work here
        }
    }
    

    Then, you'll register that type with the queue client. You can specify how many sessions you want to concurrently process, among other options:

    public override bool OnStart()
    {
        QueueClient client = ...;
        var options = new SessionHandlerOptions(){ MaxConcurrentSessions = 3 }
        client.RegisterSessionHandler(typeof(MySessionHandler), options);
    }