QueueClient.CreateFromConnectionString 是否缓存内部连接?

Does QueueClient.CreateFromConnectionString cache internal connection?

我在 ASP.NET 核心应用程序中有一个 HTTP 端点,它向 Azure 服务总线发送几条消息。

现在,控制器操作代码是这样做的:

var client = QueueClient.CreateFromConnectionString(this.connectionString, entityPath);
await client.SendAsync(message);

创建的 QueueClient 不支持 Dispose 所以我想知道它的生命周期应该有多长?我为每个 HTTP 请求创建一个新的。 QueueClient 的 CreateFromConnectionString 方法是否缓存到服务总线的内部连接?这里的最佳解决方案是什么?我问是因为我最近在流量高峰期收到了来自服务总线的 TimeoutExceptions

正如这位官员 document 提到的关于服务总线客户端:

Service Bus client objects, such as QueueClient or MessageSender, are created through a MessagingFactory object, which also provides internal management of connections. You should not close messaging factories or queue, topic, and subscription clients after you send a message, and then re-create them when you send the next message. Closing a messaging factory deletes the connection to the Service Bus service, and a new connection is established when recreating the factory. Establishing a connection is an expensive operation that you can avoid by re-using the same factory and client objects for multiple operations. You can safely use the QueueClient object for sending messages from concurrent asynchronous operations and multiple threads.

I'm asking because I've been receiving TimeoutExceptions from the service bus lately during traffic spikes.

正如官方document中提到的关于Service Bus messaging TimeoutException:

A TimeoutException indicates that a user-initiated operation is taking longer than the operation timeout. You should check the value of the ServicePointManager.DefaultConnectionLimit property, as hitting this limit can also cause a TimeoutException.

我假设您可以尝试增加 OperationTimeout 并添加如下重试逻辑来构建您的 QueueClient 并重用此 QueueClient 对象。

var builder = new ServiceBusConnectionStringBuilder("{ServicesBusConnectionString}")
{
    OperationTimeout = TimeSpan.FromMinutes(5)
};
var messagingFactory = MessagingFactory.CreateFromConnectionString(builder.ToString());
QueueClient queueClient = messagingFactory.CreateQueueClient("{queueName}");
queueClient.RetryPolicy = new RetryExponential(
                TimeSpan.Zero,
                TimeSpan.FromMinutes(5),
                2);
queueClient.SendAsync("{BrokeredMessage}");