1、使用 ConnectionFactory 创建 IConnection 时,如果有多线程的情况下,比如会有多个Consumer,需要加锁,同时确保 Connection 对象唯一,可以使用单例模式。
public bool _isConnected => _connection is { IsOpen: true };
在 RabbitMQ 持久化时,可以用到 Polly 第三方库中的 Policy 做连接失败重试。
if (_isConnected) return;
lock(obj){
var policy = Policy.Handle<SocketException>().Or<BrokerUnreachableException> ().WaitAndRetry(5,
times =>
TimeSpan.FromSeconds(Math.Pow(2, times)),
(exception, span) =>
{
Console.WriteLine(
$"rabbitmq client cannot connected. after {span.TotalSeconds:n1}. ex:{exception.Message}");
});
policy.Execute(() =>
{
var factory = new ConnectionFactory()
{
HostName = "xxxxx",
Port = 1000,
UserName = "xxxxx",
Password = "xxxxx"
};
_connection = factory.CreateConnection();
Console.WriteLine("connected to rabbitmq...");
});
if (_connection.IsOpen)
{
_connection.ConnectionShutdown += OnConnectionShutdown;
_connection.CallbackException += OnCallBackException;
_connection.ConnectionBlocked += OnConnectionBlocked;
}
else
{
Console.WriteLine(" fatal error : rabbitmq connection could not be created or opened ");
}
}
2、发布消息的时候 记得加 using 及时释放 channel
using var model = _connection.CreateModel();
3、消费者不能使用 using,否则在没有消息的时候会被释放掉。