Azure ServiceBusConnection 应该是单例的吗?

Should Azure ServiceBusConnection be singleton?

old NuGet 中,保留 MessagingFactory 实例是一种很好的做法。

我们是否应该保留 ServiceBusConnection 的单个实例(来自 new Nuget)以注入多个客户端?

编辑 2018-07-25 00:22:00 UTC+8:

不一定都是单例。

正确的级别是消息工厂。您可以连接到应用程序中的多个名称空间,每个名称空间都需要自己的 MessageFactory 和连接。

或者,您可能拥有本质上不是很异步的代码,在这种情况下,多重连接(工厂)是有意义的。例如,您的代码中有两个进程,一个在循环中执行大量工作以发送消息,另一个接收消息,在这种情况下,两个工厂可能会有用,或者您可以重构以使您的代码更加异步。

From the documentation.

It is recommended that you do 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.

简而言之,您应该重新使用您的消息工厂,然后保持与服务总线的连接。根据代码的编写方式,您可能希望拥有多个工厂。

https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-performance-improvements#reusing-factories-and-clients

Azure Service Bus .NET Standard 客户端连接不是通过 QueueClient 或任何工厂管理的,就像它的前身过去那样。 QueueClient 是在 MessageSenderMessageReceiver 之上的抽象,可以采用多个 senders/receivers 共享的 ServiceBusConnection。您可以自由选择是否共享相同的连接对象。

var connection = new ServiceBusConnection(connectionString);
var queueClient1 = new QueueClient(connection, "queue1", ReceiveMode.PeekLock, RetryPolicy.Default);
var queueClient2 = new QueueClient(connection, "queue2", ReceiveMode.PeekLock, RetryPolicy.Default);
// Queue clients share the same connection
var message1 = new Message(Encoding.UTF8.GetBytes("Message1"));
var message2 = new Message(Encoding.UTF8.GetBytes("Message2"));

根据您正在使用的命名空间层,您必须进行基准测试,看看哪种方式更适合您。我的发现表明,具有多个连接的标准层有助于吞吐量,而高级层则没有。 This post 暗示了为什么会这样。