RabbitMQ asynchronous support

2019-02-16 15:12发布

Does the RabbitMQ .NET client have any sort of asynchronous support? I'd like to be able to connect and consume messages asynchronously, but haven't found a way to do either so far.

(For consuming messages I can use the EventingBasicConsumer, but that's not a complete solution.)

Just to give some context, this is an example of how I'm working with RabbitMQ at the moment (code taken from my blog):

var factory = new ConnectionFactory() { HostName = "localhost" };

using (var connection = factory.CreateConnection())
{
    using (var channel = connection.CreateModel())
    {
        channel.QueueDeclare("testqueue", true, false, false, null);

        var consumer = new EventingBasicConsumer(channel);
        consumer.Received += Consumer_Received;
        channel.BasicConsume("testqueue", true, consumer);

        Console.ReadLine();
    }
}

3条回答
孤傲高冷的网名
2楼-- · 2019-02-16 15:28

Rabbit supports dispatching to asynchronous message handlers using the AsyncEventingBasicConsumer class. It works similarly to the EventingBasicConsumer, but allows you to register an callback which returns a Task. The callback is dispatched to and the returned Task is awaited by the RabbitMQ client.

var factory = new ConnectionFactory
{
    HostName = "localhost",
    DispatchConsumersAsync = true
};

using(var connection = cf.CreateConnection())
{
    using(var channel = conn.CreateModel())
    {
        channel.QueueDeclare("testqueue", true, false, false, null);

        var consumer = new AsyncEventingBasicConsumer(model);

        consumer.Received += async (o, a) =>
        {
            Console.WriteLine("Message Get" + a.DeliveryTag);
            await Task.Yield();
        };
    }

    Console.ReadLine();
}
查看更多
forever°为你锁心
3楼-- · 2019-02-16 15:31

there is no async/await support built in to the RabbitMQ .NET client at this point. There is an open ticket for this on the RabbitMQ .NET Client repository

查看更多
聊天终结者
4楼-- · 2019-02-16 15:34

To summarize current async/TPL support:

  • As @paul-turner mentioned, there is now an AsyncEventingBasicConsumer which you can register events for and return a Task.
  • There is also an AsyncDefaultBasicConsumer for which you can override virtual methods such as HandleBasicDeliver and return a Task. Original PR here (looks like it was also introduced in 5.0?)
  • Per the final comments on the above PR and this issue, it looks like they are working on a new, from-scratch .NET client which would more fully support async operations, but I don't see any specific links to that effort.
查看更多
登录 后发表回答