Spring Boot RabbitMQ Dead Letter Queue Configuration
This is going to be a short blog post about how to configure your Spring Boot application with a dead letter queue support for RabbitMQ.
To start let’s summarize the problem description we are trying to solve. You have a Spring Boot application which consumes messages from a RabbitMQ queue and you want the messages to be forwarded to another Rabbit queue in case a problem occurs during message processing.
Although you can implement your application to send the failed messages to a different queue manually this is not always the most effective way of handling the situation.
RabbitMQ supports dead letter exchanges and queues which are first class candidates for solving the problem we have in hand.
For a queue to be able to handle dead lettered messages it should be defined with dead letter support during creation.
In a Spring Boot application with all required dependencies added it’s simple the enable this feature.
Below spring configuration code snippet creates an exchange, defines two queues and binds both queues to the created exchange. Notice the two arguments being defined during the creation of the spring bean named queue. x-dead-letter-exchange argument is used to define the Rabbit exchange dead lettered messages will be routed to. On the other hand x-dead-letter-routing-key tags the routed messages with the routing key so they can routed to desired queue at the end.
Binding beans at the end completes the configuration by binding the queues to the exchanges with desired routing keys.
Assuming you have RabbitMQ installed and running below configuration will create the exchange, queues and bindings on your rabbit instance.
The last part that requires explanation is how to tell RabbitMQ a message should be dead lettered on your application. RabbitMQ documentation explains the events a message will be dead lettered as follows:
- The message is rejected (basic.reject or basic.nack) with requeue=false,
- The TTL for the message expires; or
- The queue length limit is exceeded.
Last two items is currently out of scope as the messages on those cases are managed by RabbitMQ itself. The first condition is the one that is relevant with our case. So the message should be rejected with basic.reject or basic.nack and requeue parameter should be set to false. Spring Rabbit hides the details gracefully and provides us a new exception class named AmqpRejectAndDontRequeueException. All you have to do on your application code is to throw this exception and Spring will handle the rest and your message will be requed. Below is a sample code snippet showing the exception in use.
This concludes the blog post. Happy coding!