首页 > 解决方案 > 如何从 Azure 服务总线主题订阅一次接收 N 条消息

问题描述

我有一个 Azure 服务总线主题订阅,其中消息不断增加。

下面的代码基本上是一次接收一条消息并处理它并将相关结果存储到数据库中。

我尝试设置 MaxConcurrentCalls to 10 ,但由于数据库工作设计,它耗尽了我的数据库连接池。

所以我想一次从订阅中获取 10 条消息(接收一批 N 条消息)并希望使用一个数据库调用进行处理。

我没有看到任何批处理 api 选项,这可能吗?

我正在使用Microsoft.Azure.ServiceBusnuget 版本4.1.1

 _subscriptionClient = new SubscriptionClient(connectionString, topicName, subscriptionName);

            // Register the callback method that will be invoked a message of interest is received
            _subscriptionClient.RegisterMessageHandler(
                async (message, token) =>
                {
                    if (await ProcessMessage(message, token))
                    {
                        await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);
                    }
                },
                new MessageHandlerOptions(ExceptionReceivedHandler) { MaxConcurrentCalls = 1, AutoComplete = false });

标签: c#asp.net-coreazure-servicebus-topicsazure-servicebus-subscriptions

解决方案


有预取的概念:https ://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-performance-improvements?tabs=net-framework-sdk#prefetching

预取使队列或订阅客户端能够在执行接收操作时从服务加载附加消息。

在此处检查接收批次: https ://docs.microsoft.com/en-us/dotnet/api/microsoft.servicebus.messaging.subscriptionclient.receivebatch ?view=azure-dotnet

例子:

SubscriptionClient client = SubscriptionClient.CreateFromConnectionString(connectionString, topic, subName);
client.PrefetchCount = 10;
IEnumerable<BrokeredMessage> messageList = client.ReceiveBatch(5);

预取应大于或等于您希望从 ReceiveBatch 接收的消息数。

预取最多可以达到每秒处理的消息数的 n/3 倍,其中 n 是默认锁定持续时间。


推荐阅读