如何在Python中使用RabbitMQ pika.basic_consume更改超时

时间:2019-08-26 00:29:13

标签: python rabbitmq pika

在运行subscriber.py的RabbitMQ Python客户端上:

    import pika, time 

    credentials = pika.PlainCredentials('user', 'pass')
    parameters = pika.ConnectionParameters(host='localhost', port=6672, credentials=credentials)
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.basic_qos(prefetch_count=1)
    channel.queue_declare(queue='my_queue')

    def callback(ch, method, properties, body):
        ch.basic_ack(delivery_tag=method.delivery_tag)
        time.sleep(600)
        print ('process completed')

    channel.basic_consume(queue='my_queue', on_message_callback=callback)
    channel.start_consuming()

callback函数完成后,连接断开。 看来它总是在第60秒发生。看来channel.basic_consume()方法不想等待主线程完成回调函数。有没有办法确保60秒后连接不会断开?

2 个答案:

答案 0 :(得分:0)

您的time.sleep呼叫阻止了Pika的I / O循环,从而阻止了心跳的处理。 不要阻止I / O循环!

相反,您应该在单独的线程中进行长时间的工作,并从该线程中正确确认消息。幸运的是,我这里有an examplelink


注意: RabbitMQ团队监视rabbitmq-users mailing list,并且有时仅在StackOverflow上回答问题。

答案 1 :(得分:0)

我认为“heartbeat”参数解决了这个问题。只需以秒为单位设置时间:

import pika, time 

credentials = pika.PlainCredentials('user', 'pass')
parameters = pika.ConnectionParameters(host='localhost', port=6672, credentials=credentials, heartbeat=36000)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
channel.basic_qos(prefetch_count=1)
channel.queue_declare(queue='my_queue')

def callback(ch, method, properties, body):
    ch.basic_ack(delivery_tag=method.delivery_tag)
    time.sleep(600)
    print ('process completed')

channel.basic_consume(queue='my_queue', on_message_callback=callback)
channel.start_consuming()