Search code examples
springspring-bootamqpspring-rabbit

Get liste of queues listen to by RabbitListener service


Can you please suggest a way to get dynamically the list of queues listen to by rabbitMQ spring RabbitListener (org.springframework.amqp.rabbit.annotation.RabbitListener)

Here is the example of my Listener which handles messages from a lot of queues (the list can be updated in the properties file) I want to get the list in another service dynamically :

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

@Service
public class GenericListener {

@RabbitListener(queues = {
                "${queue1}", "${queue2}", "${queue3}", "${queue4}", "${queue5}"
})
 public void receiveMessage(Message message) {

 }
}

the question specifically is : how to dynamically get bean interface RabbitListener params at runtime ?


Solution

  • Use the RabbitListenerEndpointRegistry bean.

    Give the listener an id; e.g. @RabbitListener(id = "foo", ...) then

    ((AbstractMessageListenerContainer) registry.getListenerContainer("foo")).getQueueNames();
    

    https://docs.spring.io/spring-amqp/docs/current/reference/html/#container-management

    Containers created for annotations are not registered with the application context. You can obtain a collection of all containers by invoking getListenerContainers() on the RabbitListenerEndpointRegistry bean. You can then iterate over this collection, for example, to stop or start all containers or invoke the Lifecycle methods on the registry itself, which will invoke the operations on each container.

    You can also get a reference to an individual container by using its id, using getListenerContainer(String id) — for example, registry.getListenerContainer("multi") for the container created by the snippet above.

    ...