解决RabbitMQ没有连接就获取通道的bug

This commit is contained in:
eithday 2025-08-26 14:35:34 +08:00
parent 85bbebf7c3
commit c220524d1d

View File

@ -21,15 +21,16 @@ public class RabbitMqConsumer : BackgroundService
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var channel = _connection.Channel;
if (channel == null)
throw new InvalidOperationException("RabbitMQ channel is null");
if (!await _connection.TryConnectAsync())
{
_logger.LogError($"RabbitMQ连接失败请检查配置文件。");
return;
}
var channel = _connection.Channel;
if (channel == null)
throw new InvalidOperationException("RabbitMQ channel is null");
await channel.QueueDeclareAsync(queue: _handler.QueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
await channel.BasicQosAsync(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new AsyncEventingBasicConsumer(channel);