How to create Synchronous consumer API for Rabbit MQ in java to fetch message from the Queue

Viewed 823

I want a Synchronous API for Rabbit MQ in java like QueueingConsumer so that I can fetch message from the Rabbit MQ. But QueueingConsumer is now deprecated. Can anyone please tell me how can I write one of my own.

Reason for Synchronous Consumer - I am writing REST service which will fetch message from Queue and return it as a response.

1 Answers

I. As I understand, you are using of rabbitmq java client. In this case you should do something like this:

  1. Generate correlationId, replyTo propertiesж
  2. Create/Get destination queue/exchange (your destination);
  3. Create/Get response queue (your queue for responses);
  4. Add correlationId and replyTo to your message;
  5. Send your message by channel.basicPublish() to queue/exchange (your destination);
  6. Subscribe to response queue by channel.basicConsume();
  7. When will you get the response message by channge.basicConsume() just check correlationId of incoming message.
  8. If correlationId is match – return received message;

Full code example here.

Also you could find comprehensive answer to your question here.

II. If you need a ready-made solution I think you could use Spring AMQP library or any other high-level library. The list of libraries can be found here.

Related