5

I have both Java and Python clients that I use channel.basicConsume(). At some point I would like to stop those consumers without stopping the entire program.

In Python with Pika I have put channel.stop_consuming() calls in place, but those generate errors that I am ignoring. Seems to work

In Java I am not sure how to do this since stop_consume() doesn't appear to be available.

All the documentation I see talks about all the ways to create consumers, but I can't seem to find anything that shows how to stop them.

What is the best way to go about this?

noisygecko
  • 1,771
  • 3
  • 15
  • 13

2 Answers2

9

The counterpart of basic_consume is basic_cancel. basic_cancel will fire the provided on_basic_cancel_ok callback function when rabbitmq has done the cancelation. Be prepared for a short period where you may still receive some messages.

See: Pika Channel

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
itsafire
  • 5,607
  • 3
  • 37
  • 48
  • Correct answer times infinite. For Java folks use [`Channel#basicCancel(String)`](http://www.rabbitmq.com/releases/rabbitmq-java-client/v3.1.5/rabbitmq-java-client-javadoc-3.1.5/com/rabbitmq/client/Channel.html#basicCancel%28java.lang.String%29). –  Sep 06 '13 at 01:07
  • Only unbind the queue if you want to stop *all* workers *and* blackhole messages sent in the interim. – djechlin Oct 22 '13 at 15:10
-2

You should be consuming in a Thread so just interrupt the that thread and leave the rest of your program running

Thread t = new Thread(){
  public void run(){
    //consumer is in here
  }
};
t.start();

// somewhere else later
t.interrupt();

You may need to make the Thread t available elsewhere buy having it as a field of the object as opposed to a local variable

robthewolf
  • 7,343
  • 3
  • 29
  • 29
  • added more info to my answer – robthewolf Apr 03 '13 at 07:16
  • This is bad for RabbitMQ, since messages will queue up. – itsafire Jul 17 '13 at 11:04
  • 3
    **This is a horrible solution:** it leaves the client in a potentially hazardous state and leaves resource (queue) leaks on the server as @itsafire mentions, whose answer BTW is the correct one. –  Sep 06 '13 at 01:06
  • I didn't put anything in the consumer code. In this part of the code you connect to the queue, if the queue is autodelete no messages will queue up as there will be no queue for them to go into. – robthewolf Sep 06 '13 at 09:13
  • 1
    What? This answer is complete B.S., like, 100% totally made up. Why on earth should you be consuming in a thread? It's not a blocking operation. So firstly, therefore you should not be consuming in a thread, and secondly, interrupting a thread wouldn't do anything since the thread will be finished anyway. Even then, how would an interrupt be handled by your hypothetical blocking `consume` function? It doesn't throw an `InterruptedException`. – djechlin Oct 22 '13 at 15:12