Mrunmaya
Mrunmaya

Reputation: 63

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?

Upvotes: 2

Views: 1365

Answers (2)

Gary Russell
Gary Russell

Reputation: 174809

If you are using Spring; you can avoid all the boilerplate in the other answer using RabbitTemplate.receive(...).

EDIT

To manually ack/reject the message, use the execute method instead.

template.execute(channel -> {
    GetResponse got = channel.basicGet("foo", false);

    // ...

    channel.basicAck(got.getEnvelope().getDeliveryTag(), false);

    return null;
});

It's a bit lower level, but again, most of the boilerplate is taken care of for you.

Upvotes: 1

Aliaksei Stadnik
Aliaksei Stadnik

Reputation: 1968

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();
   }

}

Upvotes: 2

Related Questions