在没有DispatchConsumersAsync = true的情况下解释AsyncEventingBasicConsumer行为

时间:2017-12-16 16:11:26

标签: c# asynchronous rabbitmq

我正在使用以下代码尝试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属性,则会消耗消息,但事件处理程序永远不会触发。

我发现很难相信这种危险行为(因为开发人员忘记设置属性而丢失消息)是设计使然。

问题:

  1. DispatchConsumersAsync实际上做了什么?
  2. 在没有DispatchConsumersAsync的情况下发生了什么事情,消费正在发生,但事件处理程序没有触发?
  3. 这是设计的行为吗?

0 个答案:

没有答案