Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to purge messages for Service Bus Topic Subscription

Just wondering the best way (even if via Portal, Powershell, or C#) to purge the messages off of a Service Bus Topic's Subscription.

Imagine we have a topic with 4 subscriptions, and we only want to purge the messages from one of the subscriptions.

I have a feeling the only way may be to read the messages in a while loop, but hoping for something better.

UPDATE:

Apart from using code, you can use the Server Explorer as suggested in the answer - right click subscription and purge messages:

enter image description here

like image 313
Stefan Zvonar Avatar asked Oct 25 '17 01:10

Stefan Zvonar


People also ask

What is topic and subscription in Azure Service Bus?

A topic subscription resembles a virtual queue that receives copies of the messages that are sent to the topic. Consumers receive messages from a subscription identically to the way they receive messages from a queue.

How do you clear the dead letter queue in Azure Service Bus?

Basically you connect to your Dead Letter Queue in exactly the same way as your normal queue, but you need to contatenate “$DeadLetterQueue” to the queue name. After running the following code in my unit test I successfully managed to clear all the messages from my Dead Letter Queue.


2 Answers

You can most certainly do it via code. If you're using Service Bus SDK, you could do something like the following:

    static void PurgeMessagesFromSubscription()
    {
        var connectionString = "Endpoint=sb://account-name.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=access key";
        var topic = "topic-name";
        var subscription = "subscription-name";
        int batchSize = 100;
        var subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topic, subscription, ReceiveMode.ReceiveAndDelete);
        do
        {
            var messages = subscriptionClient.ReceiveBatch(batchSize);
            if (messages.Count() == 0)
            {
                break;
            }
        }
        while (true);
    }

What this code will do is fetch messages from the subscription (100 at a time) in Receive & Delete mode so that as soon as messages are fetched, they are deleted from the subscription automatically.

I believe Service Bus Explorer tool also has the capability to purge messages. You can use that as well instead of writing the code.

like image 82
Gaurav Mantri Avatar answered Nov 11 '22 21:11

Gaurav Mantri


If you have a lot of messages and can tolerate a bit of downtime on subscriber side, it might be faster to just drop the subscription and create a new one with the same name.

like image 33
Mikhail Shilkov Avatar answered Nov 11 '22 19:11

Mikhail Shilkov