如何清除服务总线主题订阅的消息

问题描述 投票:0回答:4

只是想知道从服务总线主题的订阅中清除消息的最佳方法(即使通过 Portal、Powershell 或 C#)。

假设我们有一个包含 4 个订阅的主题,并且我们只想清除其中一个订阅中的消息。

我有一种感觉,唯一的方法可能是在 while 循环中阅读消息,但希望有更好的东西。

更新:

除了使用代码之外,您还可以按照答案中的建议使用服务器资源管理器 - 右键单击订阅并清除消息:

enter image description here

c# powershell azure azureservicebus azure-servicebus-topics
4个回答
11
投票

您当然可以通过代码来完成。如果您使用

Service Bus SDK
,您可以执行以下操作:

    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);
    }

此代码将执行的操作是以

Receive & Delete
模式从订阅中获取消息(一次 100 条),以便一旦获取消息,它们就会自动从订阅中删除。

我相信

Service Bus Explorer
工具也具有清除消息的功能。您也可以使用它来代替编写代码。


3
投票

如果您有大量消息并且可以容忍订户端的一些停机时间,那么放弃订阅并创建一个同名的新消息可能会更快。


1
投票

谢谢@Gaurav Mantri,我在 Microsoft.Azure.ServiceBus Nuget 包版本 5.2.0 中使用了稍微更改过的代码,没有使用批处理选项:

var connectionString = "Endpoint=sb://";
var topic = "topic";
var subscription = "subscription";
var subscriptionClient = new SubscriptionClient(connectionString, topic, subscription, ReceiveMode.ReceiveAndDelete);

subscriptionClient.RegisterMessageHandler(
  (message, token) =>
    {
     Console.WriteLine($"Received message: SequenceNumber: 
             {message.SystemProperties.SequenceNumber}");

      return Task.CompletedTask;
     },
   (exceptionEvent) =>
    {
     Console.WriteLine("Exception = " + exceptionEvent.Exception);
     return Task.CompletedTask;
    });

0
投票

Azure 门户中有一个清除消息选项。

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.