我正在使用以下代码尝试RabbitMQ AsyncEventingBasicConsumer
:
static void Main(string[] args)
{
Console.Title = "Consumer";
var factory = new ConnectionFactory() { DispatchConsumersAsync = true };
const string queueName = "myqueue";
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queueName, true, false, false, null);
// consumer
var consumer = new AsyncEventingBasicConsumer(channel);
consumer.Received += Consumer_Received;
channel.BasicConsume(queueName, true, consumer);
// publisher
var props = channel.CreateBasicProperties();
int i = 0;
while (true)
{
var messageBody = Encoding.UTF8.GetBytes($"Message {++i}");
channel.BasicPublish("", queueName, props, messageBody);
Thread.Sleep(50);
}
}
}
private static async Task Consumer_Received(object sender, BasicDeliverEventArgs @event)
{
var message = Encoding.UTF8.GetString(@event.Body);
Console.WriteLine($"Begin processing {message}");
await Task.Delay(250);
Console.WriteLine($"End processing {message}");
}
它按预期工作。但是,如果我没有设置DispatchConsumersAsync
属性,则会消耗消息,但事件处理程序永远不会触发。
我发现很难相信这种危险行为(因为开发人员忘记设置属性而丢失消息)是设计使然。
问题:
DispatchConsumersAsync
实际上做了什么?DispatchConsumersAsync
的情况下发生了什么事情,消费正在发生,但事件处理程序没有触发?