Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 635
user634545 Avatar asked Nov 01 '25 05:11

user634545


2 Answers

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

like image 132
Gary Russell Avatar answered Nov 03 '25 19:11

Gary Russell


To complete @user634545's last comment, we have to deal with 2 properties :

  • shutdownTimeout
  • prefetchCount

These parameters must be ajusted in order to validate the following :

prefetchCount < (shutdownTimeout / consumerExecutionTimePerMessage)

It would mean that after receiving the shutdown order, the consumer should be able to consume and aknowledge every prefetched messages.

like image 22
Alexandre D. Avatar answered Nov 03 '25 19:11

Alexandre D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!