我使用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)
但是,当队列中没有消息时,脚本就开始爬行。如何实现here中所述的get_empty()方法?
答案 0 :(得分:1)
我通过检查以下响应暂时解决了该问题:
method, properties, body = channel.basic_get(queue=FromQueue)
if(method == None):
## queue is empty
答案 1 :(得分:0)
您可以像这样检查身体是否空虚:
def callback(ch, method, properties, body):
decodeBodyInfo = body.decode('utf-8')
if decodeBodyInfo != '':
cacheResult = decodeBodyInfo
ch.stop_consuming()
那么简单易用:D
答案 2 :(得分:0)
如果您在 for 循环中使用 channel.consume
生成器,您可以设置 inactivity_timeout
参数。
来自 pika 文档,
: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
不要忘记在退出循环后正确处理通道和连接