允许RabbitMQ和Pika保持始终保持打开状态



我有一个python脚本,该脚本从流中读取内容,当读取新字符串时,它将其内容(字符串(推向兔子队列。

问题是该流可能不会在1、2或9H左右发送消息,因此我想拥有 RabbitMQ连接始终打开

问题是,当我创建计算和频道时:

self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials))
channel = self.connection.channel()
channel.exchange_declare(exchange=self.exchange_name, exchange_type='fanout')

...如果一个小时后,我会收到此错误:

  File "/usr/local/lib/python3.7/asyncio/events.py", line 88, in _run
    self._context.run(self._callback, *self._args)
  File "/var/opt/rabbitmq-agent.py", line 34, in push_to_queue
    raise Exception("Error sending the message to the queue: " + format(e))
Exception: Error sending the message to the queue: Send message to publisher error: Channel allocation requires an open connection: <SelectConnection CLOSED socket=None params=<ConnectionParameters host=x port=xvirtual_host=/ ssl=False>>

我认为该连接已在RabbitMQ服务器和客户端之间关闭。

如何避免这种情况?我想拥有一个" ,请始终保持连接始终"。也许在皮卡(Pika(的连接参数中设置超大型心跳?这样的东西:

self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials, heartbeat=6000))

任何其他冷却器溶液都将不胜感激。

预先感谢

我建议您在发送消息之前每次检查连接,如果关闭连接,则只需重新连接。

if not self.connection or self.connection.is_closed:
    self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.host, credentials=self.credentials))
    channel = self.connection.channel()
    channel.exchange_declare(exchange=self.exchange_name, exchange_type='fanout')

您可以尝试将heartbeat添加到ConnectionParameters。这将通过每指定秒发送心跳来创造轻度的流量。这将锻炼联系。一些防火墙或代理往往会刮擦空闲连接。即使是RabbitMQ也有一个暂停连接的暂停。

import pika
# Set the connection parameters to connect to rabbit-server1 on port 5672
# on the / virtual host using the username "guest" and password "guest"
credentials = pika.PlainCredentials('guest', 'guest')
parameters = pika.ConnectionParameters('rabbit-server1',
                                       5672,
                                       '/',
                                       heartbeat=60,
                                       credentials)

请参阅此处的Pika文档。

此外,您应该制定适当的代码,以减轻网络断开连接。这总是会发生并意志。因此,来自心跳的Appart有一些例外处理,准备以优雅的方式重新打开封闭的连接。

最新更新