Search code examples
springspring-amqpspring-rabbit

Spring AMQP ListenerContainer lifecycle management


We are using Spring AMQP to connect to RabbitMQ in our Spring based web application.

When we declare our listener-containers as beans (using rabbit:listener-container) in application context, their lifecycle is managed by Spring.

If we declare a listener-container in a component inside a @PostConstruct method, or we create a bean with class org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer as a prototype scoped bean, we then have to manage the lifecycle i.e. start and stop the listener-container ourselves.

My question is, if we declare new queues, bindings and listener-containers inside a @PostConstruct method, just calling listener.stop/shutdown/destroy method inside the corresponding @PreDestroy method would be enough for a graceful shutdown? Or else what do I need to do?

Note: I am guessing I don't have to do anything for the new queues and bindings created in the @PostContruct, but I would be very glad if you also confirm this for me.


Solution

  • I would not recommend starting a listener container or declaring queues/bindings in an @PostConstruct method; the context is only half-baked at that time. It might work but it's not recommended to do stuff like that while the context is being initialized.

    It's better to implement SmartLifecycle and start/stop them in the start()/stop() methods.

    Then, the container lifecycles would be indirectly managed by the spring context.

    You can also control exactly when your bean is started/stopped by putting it in a phase.