How to do error handling with EasyNetQ / RabbitMQ

后端 未结 3 1138
慢半拍i
慢半拍i 2021-02-01 20:26

I\'m using RabbitMQ in C# with the EasyNetQ library. I\'m using a pub/sub pattern here. I still have a few issues that I hope anyone can help me with:

  1. When there\'
3条回答
  •  孤街浪徒
    2021-02-01 21:08

    I've implemented exactly what you describe. Here are some tips based on my experience and related to each of your questions.

    Q1 (how to retry X times):

    For this, you can use IMessage.Body.BasicProperties.Headers. When you consume a message off an error queue, just add a header with a name that you choose. Look for this header on each message that comes into the error queue and increment it. This will give you a running retry count.

    It's very important that you have a strategy for what to do when a message exceeds the retry limit of X. You don't want to lose that message. In my case, I write the message to disk at that point. It gives you lots of helpful debugging information to come back to later, because EasyNetQ automatically wraps your originating message with error info. It also has the original message so that you can, if you like, manually (or maybe automated, through some batch re-processing code) requeue the message later in some controlled way.

    You can look at the code in the Hosepipe utility to see a good way of doing this. In fact, if you follow the pattern you see there then you can even use Hosepipe later to requeue the messages if you need to.

    Q2 (how to create an error queue per originating queue):

    You can use the EasyNetQ Advanced Bus to do this cleanly. Use IBus.Advanced.Container.Resolve to get at the conventions interface. Then you can set the conventions for the error queue naming with conventions.ErrorExchangeNamingConvention and conventions.ErrorQueueNamingConvention. In my case I set the convention to be based on the name of the originating queue so that I get a queue/queue_error pair of queues every time I create a queue.

    Q3 (how to process messages in the error queues):

    You can declare a consumer for the error queue the same way you do any other queue. Again, the AdvancedBus lets you do this cleanly by specifying that the type coming off of the queue is EasyNetQ.SystemMessage.Error. So, IAdvancedBus.Consume() will get you there. Retrying simply means republishing to the original exchange (paying attention to the retry count you put in the header (see my answer to Q1, above), and information in the Error message that you consumed off the error queue can help you find the target for republishing.

提交回复
热议问题