How to stop consuming messages from RabbitMQ using Python?

Viewed 27

Need help please.

How do I stop running Python code once there are no more messages in the queue?

Tried the following but doesn't seem to be working.

   import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()


# callback function on receiving messages
def onMessage(channel, method, properties, body):
    bodyMsg = body
    print(bodyMsg)
    return body


def Consume(queuename):
    try:
        channel.basic_consume(on_message_callback=onMessage, queue=queuename, auto_ack=True)
        q = channel.queue_declare(queue='hello')
        q_len = q.method.message_count
        channel.start_consuming()
    finally:
        stop_consuming()


# connect credentials = pika.PlainCredentials(username, password) connection = pika.BlockingConnection(
# pika.ConnectionParameters(host = server, port = port, virtual_host = vhost, credentials = credentials))
def stop_consuming(self):
    #  """Tell RabbitMQ that you would like to stop consuming by sending the
    #  Basic.Cancel RPC command.
    if self._channel:
        print('Sending a Basic.Cancel RPC command to RabbitMQ')
        self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)


Consume('hello')

Thanks

1 Answers

It is a bit unclear whether you want to stop consuming when there are no messages or if you want to stop the application.

First, you need to know if there are messages left in the queue.

I can't test if this works, but there's an answer here: Getting number of messages in a RabbitMQ queue.

Then, after each message which triggers the handler, you can check if there are messages left. If for example it states that there are 7 messages left, you could check again after 7 messages to make it a bit more efficient (this only works if you know how many consumers you'd have). Otherwise you should check it every time after a message is consumed.

If the message count is 0, you can stop the application/stop consuming the queue.

Related