在单例中包装 RabbitMQ 连接 class
Wrap RabbitMQ Connection in a singleton class
我读到过,当我使用 RabbitMQ 时,最佳做法是每个进程使用一个连接,因此我想为 rabbitmq 连接创建一个单例 class。我想使用懒惰版本的 Singleton 来自:
Implementing the Singleton Pattern in C#
我写这个class:
public class RabbitConnection
{
private static readonly Lazy<RabbitConnection> Lazy = new Lazy<RabbitConnection>(() => new RabbitConnection());
private RabbitConnection()
{
IConnectionFactory connectionFactory = new ConnectionFactory
{
HostName = "127.0.0.1",
Port = 5672,
UserName = "Username",
Password = "********"
};
Connection = connectionFactory.CreateConnection();
}
public static RabbitConnection Instance
{
get { return Lazy.Value; }
}
public IConnection Connection { get; }
}
并像这样使用:
var channel = RabbitConnection.Instance.Connection.CreateModel();
channel.QueueDeclare("myQueue", true, false, false, null);
....
这个实现是对还是错?
谢谢
I have read that when I use RabbitMQ the best practice is to use one
connection per process
不,这是不正确的。您应该根据用例需求使用尽可能多的连接,并通过使用预期工作负载的基准来确定连接/通道数。
注意: RabbitMQ 团队监控 rabbitmq-users
mailing list 并且有时只在 Whosebug 上回答问题。
我读到过,当我使用 RabbitMQ 时,最佳做法是每个进程使用一个连接,因此我想为 rabbitmq 连接创建一个单例 class。我想使用懒惰版本的 Singleton 来自: Implementing the Singleton Pattern in C#
我写这个class:
public class RabbitConnection
{
private static readonly Lazy<RabbitConnection> Lazy = new Lazy<RabbitConnection>(() => new RabbitConnection());
private RabbitConnection()
{
IConnectionFactory connectionFactory = new ConnectionFactory
{
HostName = "127.0.0.1",
Port = 5672,
UserName = "Username",
Password = "********"
};
Connection = connectionFactory.CreateConnection();
}
public static RabbitConnection Instance
{
get { return Lazy.Value; }
}
public IConnection Connection { get; }
}
并像这样使用:
var channel = RabbitConnection.Instance.Connection.CreateModel();
channel.QueueDeclare("myQueue", true, false, false, null);
....
这个实现是对还是错? 谢谢
I have read that when I use RabbitMQ the best practice is to use one connection per process
不,这是不正确的。您应该根据用例需求使用尽可能多的连接,并通过使用预期工作负载的基准来确定连接/通道数。
注意: RabbitMQ 团队监控 rabbitmq-users
mailing list 并且有时只在 Whosebug 上回答问题。