2

Actually in my RabbitMQ config I have declared 10 consumers for each queue. So all consumer threads are created before my Spring Boot application is fully up so it is taking time on application startup.

I want to lazy load all my Rabbitmq queue when my project is up. I tried using @Lazy on the configuration class but it does not seem working.

Is there any way to declare lazy load queue ?

Nivi
  • 71
  • 5

2 Answers2

2

Set autoStartup="false" on the @RabbitListener (or listener container).

Then start the listeners manually.

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

for @RabbitListener or just start() the containers if they are beans.

Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • I am configuring my listener in setMessageListener in SimpleMessageListenerContainer(not using @Rabbitlister annotation) how to start listener in this case if i have set auto startup property to false because in this case they are not registered in RabbitListenerEndpointRegistry – Nivi Jan 26 '21 at 14:28
  • 1
    You can use normal bean injection (`@Autowired` etc). – Gary Russell Jan 26 '21 at 15:15
  • I have used getBean method of ApplicationContext to inject ListenerClass bean but the listenerClass does not start listening (the Queue has already some data in it). I have also try to use @Inject to inject listenerclass but it also not working – Nivi Jan 26 '21 at 16:02
  • 1
    You need to start the `SimpleMessageListenerContainer` bean not the listener class. – Gary Russell Jan 26 '21 at 16:05
0

All you need to do is set "autoStartup=false" to @RabbitListener:

@RabbitListener(queues = "${yourqueue}",autoStartup = "false")

And then find all registered rabbit listeners and start it:

    public static void main(String[] args) {

    ConfigurableApplicationContext run = SpringApplication.run(SimPurchaseApplication.class, args);

    RabbitListenerEndpointRegistry rabbitListeners = run.getBean(RabbitListenerEndpointRegistry.class);
    for (MessageListenerContainer listenerContainer : rabbitListeners.getListenerContainers()){
        listenerContainer.start();
    }
}