Search code examples
python-3.xrabbitmqpika

Pika - Handling RabbitMQ Connection Loss


Suppose you create a channel and start consuming messages in it.

channel = get_channel()
channel.queue_declare(queue=QUEUE_NAME, durable=True)

channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback, queue=QUEUE_NAME)
channel.start_consuming()

But somehow you lose the connection to the RabbitMQ server. When connection drops, you get a ConnectionClosed exception and the consumer stops. How should one handle connection loss in pika when in consumer mode?


Solution

  • I ended up ditching pika and using kombu instead. You can build a robust consumer (which will reconnect if connection drops) as described in this article:

    https://medium.com/python-pandemonium/building-robust-rabbitmq-consumers-with-python-and-kombu-part-1-ccd660d17271