Search code examples
spring-bootrabbitmqspring-amqp

How to consume message from RabbitMQ dead letter queue one by one


The requirement is like to process the messages from dead letter queue by exposed a REST service API(Spring Boot). So that once REST service is called, one message will be consumed from the DL queue and will publish in the main queue again for processing. @RabbitListener(queues = "QUEUE_NAME") consumes the message immediately which is not required as per the scenario. The message only has to be consumed by the REST service API. Any suggestion or solution?


Solution

  • I do not think RabbitListener will help here.

    However you could implement this behaviour manually.

    Spring Boot automatically creates RabbitMq connection factory so you could use it. When http call is made just read single message from the queue manually, you could use basic.get to synchronously get just one message:

    @Autowire 
    private ConnectionFactory factory 
    
    void readSingleMessage() {
       Connection connection = null;
       Channel channel = null;
       try {
          connection = factory.newConnection();
          channel = connection.createChannel();
    
          channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    
          GetResponse response = channel.basicGet(QUEUE_NAME, true);
          if (response != null) {
             //Do something with the message
          }
       } finally {
         //Check if not null
         channel.close();
         connection.close();
       }
    
    }