简体   繁体   English

在可读队列python中关闭连接

[英]Close connection in readable queue python

When the microservice takes a message from RabbitMQ and the data is processed for a long time, and the connection is closed with the queue that is on the wiretap 当微服务从RabbitMQ接收消息并长时间处理数据,并且连接被窃听时的队列关闭时

Traceback (most recent call last):
  File "/home/saturn/Logic/MAIN_1.py", line 200, in <module>
    channel.start_consuming()
  File "/usr/local/lib/python3.5/dist-packages/pika/adapters/blocking_connection.py", line 1780, in start_consuming
    self.connection.process_data_events(time_limit=None)
  File "/usr/local/lib/python3.5/dist-packages/pika/adapters/blocking_connection.py", line 707, in process_data_events
    self._flush_output(common_terminator)
  File "/usr/local/lib/python3.5/dist-packages/pika/adapters/blocking_connection.py", line 474, in _flush_output
result.reason_text)
pika.exceptions.ConnectionClosed: (-1, "ConnectionResetError(104, 'Connection reset by peer')") 

Now task processing near 5 minutes. 现在任务处理将近5分钟。 Main code like - 主要代码-

credentials = pika.PlainCredentials(username='NAME',password='PASSWORD')
ConnParr = pika.ConnectionParameters(host='HOST', credentials=credentials)
connection = pika.BlockingConnection(ConnParr)
channel = connection.channel()

def callback(ch, method, properties, body):
    in_data = json.loads(body.decode('utf-8'))
    main(in_data)
    ch.basic_ack(delivery_tag=method.delivery_tag)

def main(in_data):
    time.sleep(300)

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

This is happening because the time.sleep call blocks your main thread and prevents Pika from sending and receiving heartbeat messages from RabbitMQ. 发生这种情况是因为time.sleep调用阻塞了您的主线程,并阻止了Pika从RabbitMQ发送和接收心跳消息。 You have a couple ways to fix this: 您有几种方法可以解决此问题:

  • Upgrade to Pika 0.12.0 , run your main method in a separate thread, and use add_callback_threadsafe in that thread to call basic_ack on the channel docs . 升级到Pika 0.12.0 ,在单独的线程中运行您的main方法,然后在该线程中使用add_callback_threadsafe调用channel docs上的basic_ack

  • Use the asynchronous consumer example as a starting point for your code. 使用异步使用者示例作为代码的起点。

The important part to remember is that you can't block Pika's internal event loops and expect the connection to stay alive. 要记住的重要部分是,您不能阻止Pika的内部事件循环,也不能期望连接保持活动状态。 If you need further assistance, Pika's maintainers (me among others) monitor the rabbitmq-users and pika-python mailing lists for questions. 如果您需要进一步的帮助,Pika的维护者(包括我在内)将监视rabbitmq-userspika-python邮件列表是否有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM