Right way to cancel rabbitmq consuming with pika

Question:

I want to implement rpc client using rabbitmq. My code primarily looks like

def start(self):
    while True:
        self.channel.basic_consume(self.on_delivery)
 ...
 client.start() // blocking call

What is right way to stop this client ?
Now I make channel.basic_cancel(self.on_cancel, self.consumer_tag) from another thread. However pika faq says It is not safe to share one Pika connection across threads.

What is preferred way to cancel consuming ?

Asked By: sergeyz

||

Answers:

As long as you create one connection per thread, you should be fine.

eandersson created an example of this here.

Answered By: Drewness

If you want use basic_cancel see this gist

you can see code briefly like below:

def callback(ct, ch, method, properties, body):
   ...
   ch.basic_cancel(consumer_tag=ct, nowait=False) # WARNING no such parameter `nowait` please remove from method call
   ...

...
consumer_tag = uuid.uuid1().hex
channel.basic_consume(partial(callback, consumer_tag),
                              queue=queue_name,
                              consumer_tag=consumer_tag) # add consumer_tag
...

in [email protected] there is no such parameter named nowait, so you just remove it from method call.

Answered By: Yoooda
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.