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

近期使用rabbitmq,python2.7,pika 0.10.0,想要判断connection和channel是否open,但是用connection里的is_closed()和is_open()似乎不生效。
我的测试代码如下:
程序运行后,即使我重启了rabbitmq所在的机器,打印的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)

下面是每隔5s打印一次的结果,一直是没变的,即使当中重启了rabbitmq所在的机器也是这样。不知道究竟如何判断当前连接的状态呢?因为发现断链的话,要重新进行连接。
图片描述

阅读 7.8k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进