Requeueable Message Listener Pattern¶
The Requeueable Message Listener Pattern is a design approach for message consumers that handles processing failures by explicitly requeueing messages to the original message broker (e.g., RabbitMQ) rather than relying on the broker's native redelivery mechanism or dead-letter queues.^[001-TODO__code_copy.md]
Core Implementation¶
This pattern typically involves a base listener class that provides a reusable mechanism for catching exceptions during message processing and initiating the requeue logic.^[001-TODO__code_copy.md]
A specific implementation often involves:
1. Wrapping the business logic: The actual message processing is encapsulated, often within a lambda expression or a Functional Interface, allowing the wrapper to handle flow control.
2. RequeueInfo configuration: The wrapper accepts a context object (RequeueInfo) that contains the necessary routing details (such as the target Exchange and Queue) to send the message back to the broker.
3. Publisher-Confirm reliance: The sending operation is assumed to be reliable (e.g., using a Sender wrapper with publisher confirms enabled), ensuring that the message is successfully placed back into the queue before the consumer transaction completes.^[001-TODO__code_copy.md]
Usage Example¶
In a report generation system, this pattern is applied to handle asynchronous tasks where failure is possible but recoverable, or where a delayed retry is required.
For instance, a listener consuming from a common report queue (MONITOR_RUN_FAILURE_Q) uses the processMessageOrRequeue method.^[001-TODO__code_copy.md] If the processing logic fails, the system catches the exception and uses the rabbitSender to republish the message to a specific delay queue (DELAY_QUEUE_Q), effectively scheduling a retry for a later time without losing the original payload.^[001-TODO__code_copy.md]
Benefits¶
- Customized Retry Logic: Unlike standard broker redelivery (which might retry immediately), this pattern allows the consumer to route the message to a different destination, such as a delay queue, to control the timing of retries.^[001-TODO__code_copy.md]
- Context Awareness: The consumer can decide to requeue based on specific business logic or exception types, rather than just connection failures.
- State Preservation: Since the message is resent as a new message, it preserves the processing state and ensures it remains in the messaging system until successfully processed or explicitly moved to a dead-letter queue.
Related Concepts¶
- [[Dead Letter Queue]]
- [[Message Broker]]
- [[Spring AMQP]]
Sources¶
^[001-TODO__code_copy.md]