Reputation: 33
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
Reputation: 174729
There are a few options.
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.
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.
Create a SimpleMessageListenerContainer
(or DirectMessageListenerContainer
) dynamically and start/stop it as needed.
...
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