RabbitMQ asynchronous support

后端 未结 4 2031
眼角桃花
眼角桃花 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 17:19

    There is AsyncEventingBasicConsumer and all that it does, is awaiting your async "event handlers" when message is received. That's the only thing that is made asynchronous here. Typically you don't get any profits from this, because you have only one "handler". Messages are still processed one-by-one. They are processed synchronously! Also you lose control of exception handling because awaiting is done inside Consumer.

    Let me guess that by asynchronous message processing you mean some degree of parallelism.

    What i ended up using is ActionBlock from TPL Dataflow. ActionBlock runs as much tasks as you configured it to, managing awaits and parellelism. Since it operates on Tasks, not Threads, it can manage with less resources, as long as they are truly asynchronous.

    1. Regular EventingBasicConsumer calls actionBlock.Post(something).
    2. For parallel processing you need to tell RMQ to send you N messages before you ack them: model.BasicQos(0, N, true);
    3. ActionBlock has options with MaxDegreeOfParallelism property which also needs to be set to N.
    4. ActionBlock runs async Tasks which receive data posted earlier by Consumer. Tasks should not throw because ActionBlock stops all processing on exceptions.
    5. Be careful to pass CancellationToken around and correctly wait for ActionBlock to finish all running Tasks: actionBlock.Complete(); await actionBlock.Completion;

提交回复
热议问题