Python 3.x 如何使用Pika和Python检查RabbitMQ中是否没有消息

Python 3.x 如何使用Pika和Python检查RabbitMQ中是否没有消息,python-3.x,rabbitmq,python-pika,Python 3.x,Rabbitmq,Python Pika,我使用pika python库从RabbitMQ读取消息。读取循环中的消息由 connection = rpc.connect() channel = connection.channel() channel.basic_consume(rpc.consumeCallback, queue=FromQueue, no_ack=Ack) channel.start_consuming() 这个很好用。 但我也需要阅读一条信息,我会这样做: method, properties, body = c

我使用pika python库从RabbitMQ读取消息。读取循环中的消息由

connection = rpc.connect()
channel = connection.channel()
channel.basic_consume(rpc.consumeCallback, queue=FromQueue, no_ack=Ack)
channel.start_consuming()
这个很好用。 但我也需要阅读一条信息,我会这样做:

method, properties, body = channel.basic_get(queue=FromQueue)
rpc.consumeCallback(Channel=channel,Method=method, Properties=properties,Body=body)

但是,当队列中没有消息时,脚本将崩溃。如何实现所描述的get_empty()方法?

我通过检查响应暂时解决了这个问题,如:

method, properties, body = channel.basic_get(queue=FromQueue)
if(method == None):
    ## queue is empty

您可以按如下方式在正文中检查空:

def callback(ch, method, properties, body):
    decodeBodyInfo = body.decode('utf-8')
    if decodeBodyInfo != '':
        cacheResult = decodeBodyInfo
        ch.stop_consuming()

这非常简单且易于使用:D

如果您正在使用for循环中的
通道。使用
生成器,您可以设置
非活动\u超时
参数

从皮卡文件中

:param float inactivity_timeout: if a number is given (in seconds), will cause the
method to yield (None, None, None) after the given period of inactivity; this 
permits for pseudo-regular maintenance activities to be carried out by the user 
while waiting for messages to arrive. If None is given (default), then the method 
blocks until the next event arrives. NOTE that timing granularity is limited by the 
timer resolution of the underlying implementation.NEW in pika 0.10.0.
因此,将代码更改为这样可能会有所帮助

        for method_frame, properties, body in channel.consume(queue, inactivity_timeout=120):

            # break of the loop after 2 min of inactivity (no new item fetched)
            if method_frame is None
                break

退出环路后,不要忘记正确处理通道和连接。

通道处于阻塞状态。如何调用
频道.basic\u get
?你使用的是单独的线程吗?不,我使用其中任何一个。这是一个决定使用哪一个的参数。