6.3. 配置重新连接
重新连接可让客户端从丢失的连接中恢复。它用于确保分布式系统中的组件在临时网络或组件故障后重新建立通信。
AMQ Python 默认启用重新连接。如果连接丢失或连接尝试失败,客户端会在短暂延迟后重试。每次新尝试时,延迟会增加指数,最多为 10 秒。
要禁用重新连接,请将 重新连接 选项设置为 False。
示例:禁用重新连接
container.connect("amqp://example.com", reconnect=False)
要控制连接尝试之间的延迟,请定义一个实施 reset () 和 next () 方法的类,并将 重新连接 选项设置为该类的实例。
示例:配置重新连接
class ExampleReconnect(object):
def __init__(self):
self.delay = 0
def reset(self):
self.delay = 0
def next(self):
if self.delay == 0:
self.delay = 0.1
else:
self.delay = min(10, 2 * self.delay)
return self.delay
container.connect("amqp://example.com", reconnect=ExampleReconnect())
下一个 方法返回下一次延迟(以秒为单位)。在重新连接过程开始前,会调用 reset 方法。