[rabbitmq-discuss] How to shutdown cleanly a Java application using Consumers?

Bertrand Guay-Paquet bernie at step.polymtl.ca
Wed Apr 2 22:52:00 BST 2014


Thanks Jason and Gary,

Your replies really helped and I almost got it now. At first, I didn't 
know that handleCancelOk only runs when a consumer is not handling 
anything else. That is, only a single handle*() method can run at the 
same time on any given consumer instance. Thinking about it now, I 
realize this was explained in the doc with the phrase "Each Channel has 
its own dispatch thread."

So I created my subclass of DefaultConsumer (BasicConsumer) which 
implements isCancelled() and handleCancelOk() which sets a "cancelled 
flag" to true. Is there already a built-in way to know if a consumer was 
cancelled? I couldn't find it myself...

Here are my start and stop sequences which almost completely work. I 
haven't found how to forcefully stop a badly behaving Consumer after a 
given timeout at the end of the stop sequence. How can this be achieved?

Start sequence:
consumers = new ArrayList<BasicConsumer>();
consumers.add(...)

Stop sequence:
// Cancel all consumers
for (BasicConsumer consumer : consumers) {
   try {
     consumer.getChannel().basicCancel(consumer.getConsumerTag());
   } catch (Exception e) {
     // report
   }
}

// Wait for all consumers to be cancelled
Timeout timeout = ...;
while (!consumers.isEmpty() && !timeout.isElapsed()) {
   // Remove cancelled consumers
   for (Iterator<BasicConsumer> iterator = consumers.iterator(); 
iterator.hasNext();) {
     if (iterator.next().isCancelled())
       iterator.remove();
   }
}

// Force close remaining (timed-out) consumers
for (BasicConsumer consumer : consumers) {
   consumer.getChannel().abort(); // <---- doesn'k kill the consumer
   // <---------------- How do I kill a timed-out consumer?
}
connection.close();

Regards,
Bertrand


More information about the rabbitmq-discuss mailing list