首页 > 解决方案 > 带有 python pika 库的 Rabbit MQ StreamLostError

问题描述

当我使用 python pika 库收听队列时,我总是得到 StreamLostError 并且我的代码崩溃了。

在我的代码中,我必须无一例外地永远监听队列,并且我必须逐个获取消息。

这是我的代码(我简化了它)。

def callback(ch, method, properties, body):
   ch.basic_ack(delivery_tag = method.delivery_tag)
   #doing work here, it gets minimum 5 minutes, sometimes maximum 1 hour

credentials = pika.PlainCredentials(username, password)
parameters = pika.ConnectionParameters(ip, port, '/', credentials)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.basic_qos(prefetch_count=1)
channel.queue_declare(queue=queuename, durable=True)
channel.basic_consume(queue=queuename, on_message_callback=callback, auto_ack=False)
channel.start_consuming()  

标签: pythonrabbitmqpika

解决方案


问题是您的工作耗时太长,并且阻塞了 Pika 的 I/O 循环。这会导致心跳丢失,并且 RabbitMQ 认为您的连接已死。

请参阅此代码,了解一种进行长时间运行的正确方法:

https://github.com/pika/pika/blob/master/examples/basic_consumer_threaded.py


注意: RabbitMQ 团队会监控rabbitmq-users 邮件列表,有时只会在 StackOverflow 上回答问题。


推荐阅读