Jero Su
Jero Su

Reputation: 33

spring-RabbitMQ manually listen to queue

I'm new in rabbitmq.I'm using spring-amqp to implement the feature. As we know spring provide @RabbitListener to register a listener to queue when the app initialization. I want to design a function when I click some button, a new consumer will be created and listen to a specified queue. Java base provide channel.basicConsume() method to consume a queue. Is spring provide such function ?

I want to implement like :

producer keep sending messages to a fanout exchange. when a consume wants to join, call function1 -> create queue and binding to exchange -> consume messages.
when a consume wants leave, call function2 -> disconnect

Upvotes: 3

Views: 2965

Answers (1)

Gary Russell
Gary Russell

Reputation: 174729

There are a few options.

  1. Use one of the RabbitTemplate.receive() or convertAndReceive() methods to get messages one-at-a-time, you can set a receiveTimeout in case there are no messages.

  2. RabbitTemplate.execute() with a callback that gets a channel that you can call basicConsume() on. This is a lower-level option and won't do any conversion for you.

  3. Create a SimpleMessageListenerContainer (or DirectMessageListenerContainer) dynamically and start/stop it as needed.

  4. ...

In all cases, you can use a RabbitAdmin to create/bind the queue, for all except option 1, it would probably an auto-delete queue that will be removed when the consumer is cancelled. With option 1, you would have to use a non-auto-delete queue and remove it with the RabbitAdmin.

I would suggest that #3 is the most efficient using pure Spring AMQP.

You could also use Spring Integration with an inbound channel adapter and a publish-subscribe channel; that way you only need one queue (per application instance) and then subscribe a new MessageHandler to the channel for each user.

Upvotes: 5

Related Questions