Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Service Bus in .Net Core - how to receive only one message

I'd like to use Azure Service Bus on .Net Core and read only one message. It seems that Microsoft.Azure.ServiceBus does not support such a case. So far testing code a bit got me this far:

public void ReceiveOne()
{
    var queueClient = new QueueClient(ServiceBusConnectionString, "go_testing");

    queueClient.RegisterMessageHandler(
        async (message, token) =>
        {
            var messageBody = Encoding.UTF8.GetString(message.Body);
            Console.WriteLine($"Received: {messageBody}, time: {DateTime.Now}");
            await queueClient.CompleteAsync(message.SystemProperties.LockToken);

            await queueClient.CloseAsync();
        },
        new MessageHandlerOptions(async args => Console.WriteLine(args.Exception))
        { MaxConcurrentCalls = 1, AutoComplete = false });
}

So I'm closing queue after successfully reading one message. It works, but it also triggers an exception.

Do you know a better way to achieve it?

like image 221
Mik Avatar asked May 20 '18 19:05

Mik


1 Answers

I found a solution:

IMessageReceiver messageReceiver = new MessageReceiver(ServiceBusConnectionString, QueueName, ReceiveMode.PeekLock);

// Receive the message
Message message = await messageReceiver.ReceiveAsync();

// Process the message
Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

// Complete the message so that it is not received again.
// This can be done only if the MessageReceiver is created in ReceiveMode.PeekLock mode (which is default).
await messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
await messageReceiver.CloseAsync();

You will need to include:

using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Core;

This is the original source: https://github.com/Azure/azure-service-bus/tree/master/samples/DotNet/GettingStarted/Microsoft.Azure.ServiceBus/SendReceiveUsingMessageSenderReceiver

like image 198
hujtomi Avatar answered Oct 16 '22 13:10

hujtomi