[321]rabbitMQ连接断开问题

猜测:pika客户端没有及时发送心跳,连接被server断开

一开始修改了heartbeat_interval参数值, 示例如下:

def test_main():
    s_conn = pika.BlockingConnection(
        pika.ConnectionParameters('127.0.0.1', 
            heartbeat_interval=10,
            socket_timeout=5,
            credentials=pika.PlainCredentials(USER, PWD)))
    # ....

去看它的api,看到heartbeat_interval的解析:

:param int heartbeat_interval: How often to send heartbeats.
                                  Min between this value and server's proposal
                                  will be used. Use 0 to deactivate heartbeats
                                  and None to accept server's proposal.

按这样说法,应该还是没有把心跳值给设置好。上面的程序期望是10秒发一次心跳,但是理论上发送心跳的间隔会比10秒多一点。所以艾玛,我应该是把heartbeat_interval的作用搞错了, 它是指超过这个时间间隔不发心跳或不给server任何信息,server就会断开连接, 而不是说pika会按这个间隔来发心跳。 结果我把heartbeat_interval值设置高一点(比实际发送心跳/信息的间隔更长),比如上面设置成60秒,就正常运行了。

如果不指定heartbeat_interval, 它默认为None, 意味着按rabbitMQ server的配置来检测心跳是否正常。
如果设置heartbeat_interval=0, 意味着不检测心跳,server端将不会主动断开连接。

使用pika库,如何判断connection和channel是open还是closed的?

想要判断connection和channel是否open,但是用connection里的is_closed()和is_open()似乎不生效。

#!/usr/bin/env python  
import pika  
import time  


credit = pika.PlainCredentials(username='cloud', password='cloud')

connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='10.32.1.12', credentials=credit))

channel = connection.channel()  

while True:
    connect_close = connection.is_closed
    connect_open = connection.is_open
    channel_close = channel.is_closed
    channel_open = channel.is_open
    
    print("connection is_closed ", connect_close)
    print("connection is_open ", connect_open)
    print("channel is_closed ", channel_close)
    print("channel is_open ", channel_open)
    print("")
    time.sleep(5)

参考:https://segmentfault.com/q/1010000011299922

你可能感兴趣的:(异常)