RabbitMQ asynchronous support

后端 未结 4 1993
眼角桃花
眼角桃花 2020-12-09 16:28

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 eith

4条回答
  •  时光说笑
    2020-12-09 16:56

    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();
    }
    

提交回复
热议问题