.NET Core Azure servicebusqueue 消息数

.NET Core Azure servicebusqueue number of messages

我目前正在开发一个 .NET Core 项目,我在该项目中使用了 Microsoft.Azure.Servicebus 1.0 版 NuGet 包:https://github.com/Azure/azure-service-bus

我遇到的问题是我没有找到任何方法来获取队列的活动消息数。这在使用 ServicebusNamespace.NamespaceManager 的 .NET 框架中非常容易,引用队列并使用 .ActiveMessageCount.

在这个带有 .NET Core 1.1 的库中是否可以通过其他方式实现?

.NET Standard 客户端 (Microsoft.Azure.ServiceBus) 故意不提供管理操作。它指出不应在 运行 时间执行管理操作。管理操作极慢。

Is this possible in some other way in this library with .NET Core 1.1?

是的,有可能。

代替旧客户端 (WindowsAzure.ServiceBus) 可用的 NamespaceManager,有一个 ServiceBus 管理库 (Microsoft.Azure.Management.ServiceBus.Fluent)

您需要执行以下操作:

  • 使用 ServiceBusManager
  • 进行身份验证
  • 通过ServiceBusManager.Namespaces
  • 访问您感兴趣的命名空间
  • 通过在 ServiceBusManager.Namespaces.Queues/ServiceBusManager.Namespaces.Topics 下找到您感兴趣的实体来过滤掉它。对于订阅,您需要通过 ITopic 对象找到一个。
  • 获得实体(IQueueITopicISubscription)后,您将能够访问消息计数。

我不太喜欢这种方法。与其让每个开发人员重新发明这个轮子,Azure 服务总线团队应该提供一个帮助程序库来替换 NamespaceManger。你总是可以 raise an issue or vote for an issue that was closed.

管理操作是在版本 3.1.1 中引入的 pull request #481

现在可以使用最新版本的 Service Bus library (3.1.1):

using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Management;

var client = new ManagementClient(connectionString);
var queue = await client.GetQueueRuntimeInfoAsync(queuePath);
var counts = queue.MessageCountDetails;

var subs = await client.GetSubscriptionRuntimeInfoAsync(topic, subscription);
var countForThisSubscription = subs.MessageCount;  //// (Comes back as a Long.)