Search code examples
c#.netazureazureservicebus

How to peek all messages in Azure Service Bus queue?


I'd like to peek all messages from several Azure Service Bus queues. After that I want to filter them after queueName, insertDate and give the opportunity to make a full text search on the body.

Currently, I'm using the Microsoft.Azure.ServiceBus package to create a ManagementClient for gathering queue information and then use a MessageReceiver to peek the messages.

var managementClient = new ManagementClient(connectionString);

var queue = await managementClient.GetQueueRuntimeInfoAsync(queueName);

var count = queue.MessageCount;

var receiver = new MessageReceiver(connectionString, queueName);

var messagesOfQueue = new List<Message>();

for (var i = 1; i <= count; i++)
{
   messagesOfQueue.Add(await receiver.PeekAsync());
}

Is there a better way to get all messages? Or is there even a way to only peek messages that apply to a filter?

I've also tried to use the QueueClient.PeekBatch Method from the WindowsAzure.ServiceBus package. But that method didn't return all messages although I've set the correct messageCount parameter.

And then there is also the package Azure.Messaging.ServiceBus... What's up with all these packages?

So which of the packages should I use and what is the best way for peeking messages of queues based on some filters?


Solution

  • The solution I'm currently using and which works as expected looks like this:

    var receiver = serviceBusClient.CreateReceiver(queueName);
    
    var messagesOfQueue = new List<ServiceBusReceivedMessage>();
    var previousSequenceNumber = -1L;
    var sequenceNumber = 0L;
    
    do
    {
      var messageBatch = await receiver.PeekMessagesAsync(int.MaxValue, sequenceNumber);
    
      if (messageBatch.Count > 0)
      {
        sequenceNumber = messageBatch[^1].SequenceNumber;
    
        if (sequenceNumber == previousSequenceNumber)
          break;
    
        messagesOfQueue.AddRange(messageBatch);
    
        previousSequenceNumber = sequenceNumber;
      }
      else
      {
        break;
      }
    } while (true);
    

    It uses the nuget package Azure.Messaging.ServiceBus.