Read messages from Azure ServiceBus Queue
Read messages from Azure ServiceBus Queue using dotnet core and Azure SDK
In this post, I will show you how to read messages from an Azure ServiceBus Queue using dotnet core and Azure SDK.
Prerequisites
- Azure Subscription
- Azure ServiceBus Namespace
- Azure ServiceBus Queue
- Azure ServiceBus Connection String
Create a new dotnet core console application
Create a new dotnet core console application using the following command:
1
2
dotnet new console -n ReadMessagesFromServiceBusQueue
cd ReadMessagesFromServiceBusQueue
Install Azure.Messaging.ServiceBus package
Install the Azure.Messaging.ServiceBus
package using the following command:
1
dotnet add package Azure.Messaging.ServiceBus
Read messages from Azure ServiceBus Queue
Add the following code in Program.cs
file to read messages from the Azure ServiceBus Queue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
namespace ReadMessagesFromServiceBusQueue
{
class Program
{
static async Task Main(string[] args)
{
string connectionString = "<connection-string>";
string queueName = "<queue-name>";
await ReadMessagesFromQueue(connectionString, queueName);
}
static async Task ReadMessagesFromQueue(string connectionString, string queueName)
{
await using var client = new ServiceBusClient(connectionString);
ServiceBusReceiver receiver = client.CreateReceiver(queueName);
while (true)
{
ServiceBusReceivedMessage message = await receiver.ReceiveMessageAsync();
if (message != null)
{
Console.WriteLine($"Received message: {message.Body}");
await receiver.CompleteMessageAsync(message);
}
}
}
static async Task PublishMessagesToQueue(string connectionString, string queueName)
{
await using var client = new ServiceBusClient(connectionString);
ServiceBusSender sender = client.CreateSender(queueName);
for (int i = 0; i < 10; i++)
{
ServiceBusMessage message = new ServiceBusMessage($"Message {i}");
await sender.SendMessageAsync(message);
Console.WriteLine($"Sent message: {message.Body}");
}
}
}
}
Replace the <connection-string>
and <queue-name>
placeholders with your Azure ServiceBus Connection String and Queue Name.
Run the application
1
dotnet run
The application will start reading messages from the Azure ServiceBus Queue. You should see all the published messages in the console. To close the application, press Ctrl+C
.
That’s it. You have successfully read messages from an Azure ServiceBus Queue using dotnet core and Azure SDK.
I hope you find this post helpful. Please let me know your thoughts in the comments below.
This is a very simple example to get you started. In a real-world scenario, you should handle exceptions, DI, logging, and other best practices.