Search code examples
javaspringrabbitmqspring-amqpspring-rabbit

How to gracefully stop consuming messages with @RabbitListener


Is there a way to gracefully stop a ListenerContainer, and its associated Consumers.

What I'm trying to achieve.

  1. Stop consuming messages.
  2. Gracefully stop ListenerContainer.
  3. Await long running consumers, and ack when finished.

I'm able to stop the ListenerContainers using consumer.stop(), but active long running consumers won't complete successfully, and processed messages won't be acked and will therefore be processed again, once the ListenerContainer has been resumed.

Output

Waiting for workers to finish.
Workers not finished.
Closing channel for unresponsive consumer: Consumer@6d229b1c

The message was processed, but not acked.

I might be able to achieve a graceful shutdown using setForceCloseChannel(false), but is it possible to verify if the cancelled consumers has finished? SimpleMessageListenerContainer.doShutDown() has a local scoped List "canceledConsumers".


Solution

  • Increase the shutdown timeout.

    See Message Listener Container Configuration.

    shutdownTimeout

    When a container shuts down (for example, if its enclosing ApplicationContext is closed), it waits for in-flight messages to be processed up to this limit. Defaults to five seconds.

    /**
     * The time to wait for workers in milliseconds after the container is stopped. If any
     * workers are active when the shutdown signal comes they will be allowed to finish
     * processing as long as they can finish within this timeout. Defaults
     * to 5 seconds.
     * @param shutdownTimeout the shutdown timeout to set
     */
    public void setShutdownTimeout(long shutdownTimeout) {
    

    EDIT

    There is now a new property forceStop to stop the container after the current message is processed, requeueing other prefetched messages. https://docs.spring.io/spring-amqp/docs/current/reference/html/#forceStop