EIP – Azure Service Bus Channel Purger
Post by: syed hussain in All C# Integration Design Patterns
Summary
Channel Purger is an Enterprise Integration Design pattern where a message channel is purged or reset of all messages.
There are two methods to purge an Azure Service Bus channel:
- Loop through all the messages and remove each message from the channel.
- Delete the Queue and create the same Queue again.
There isn’t an official way or method to empty an Azure Service Bus Queue using the Nuget assemblies. The following approach loops through the message list and empties the contents from a Queue.
Delete & Create an Azure Service Bus Queue
internal static async Task EntitiesQueue(string connectionString, string queueName)
{
client = new ServiceBusClient(connectionString);
sender = client.CreateSender(queueName);
// Delete the ServiceBus Queue
ServiceBusReceiver receiver = client.CreateReceiver(queueName,
new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete });
while ((await receiver.PeekMessageAsync()) != null)
{
// receive in batches of 100 messages.
await receiver.ReceiveMessagesAsync(100);
}
// create a batch
using ServiceBusMessageBatch messageBatch = await sender.CreateMessageBatchAsync();
foreach (var result in Collections._GlobalEntityCol)
{
// try adding a message to the batch
if (!messageBatch.TryAddMessage(new ServiceBusMessage($"{result["logicalname"]}")))
{
// if it is too large for the batch
throw new Exception($"The message {result["logicalname"]} is too large to fit in the batch.");
}
}
try
{
// Use the producer client to send the batch of messages to the Service Bus queue
await sender.SendMessagesAsync(messageBatch);
Console.WriteLine($"A batch of {numOfMessages} messages has been published to the queue.");
}
finally
{
// Calling DisposeAsync on client types is required to ensure that network resources
// and other unmanaged objects are properly cleaned up.
await sender.DisposeAsync();
await client.DisposeAsync();
}
}
The code responsible for deleting all contents of a Queue
// Delete the ServiceBus Queue
ServiceBusReceiver receiver = client.CreateReceiver(queueName,
new ServiceBusReceiverOptions { ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete });
while ((await receiver.PeekMessageAsync()) != null)
{
// receive in batches of 100 messages.
await receiver.ReceiveMessagesAsync(100);
}
Tags: azure service bus