I’ve recently been working on a little project to detect the location and state of service bus messages.
One of the things that I needed to do with this was to work out how many messages were in a queue (by queue, read queue or subscription). It turns out that there’s a relatively easy way - using the ServiceBusAdministrationClient. There’s a very useful set of methods in this class:
GetSubscriptionRuntimePropertiesAsync
GetQueuesRuntimePropertiesAsync
You can also get data about the topic itself:
GetTopicRuntimePropertiesAsync
Here’s an example of its usage:
var subscriptionInformation = (await serviceBusManagementClient.GetSubscriptionRuntimePropertiesAsync(
topicName, subscription)).Value;
_logger.LogInformation($"Subscription: {subscription}, active messages: {subscriptionInformation.ActiveMessageCount}");
Admittedly, it’s a niche use-case, but it is useful!