等待一个RabbitMQ消息超时 [英] Wait for a single RabbitMQ message with a timeout
问题描述
我想向RabbitMQ服务器发送一条消息,然后等待答复消息(在答复队列中)。当然,我不想永远等待,以防处理这些消息的应用程序关闭-需要超时。听起来这是一项非常基本的任务,但我找不到解决方法。我现在同时遇到 py-amqplib 和 RabbitMQ .NET客户端。
I'd like to send a message to a RabbitMQ server and then wait for a reply message (on a "reply-to" queue). Of course, I don't want to wait forever in case the application processing these messages is down - there needs to be a timeout. It sounds like a very basic task, yet I can't find a way to do this. I've now run into this problem with both py-amqplib and the RabbitMQ .NET client.
我最好的解决方案到目前为止,已经使用 basic_get
和 sleep
进行了轮询,但这很丑陋:
The best solution I've got so far is to poll using basic_get
with sleep
in-between, but this is pretty ugly:
def _wait_for_message_with_timeout(channel, queue_name, timeout):
slept = 0
sleep_interval = 0.1
while slept < timeout:
reply = channel.basic_get(queue_name)
if reply is not None:
return reply
time.sleep(sleep_interval)
slept += sleep_interval
raise Exception('Timeout (%g seconds) expired while waiting for an MQ response.' % timeout)
肯定有更好的方法吗?
推荐答案
我刚刚添加了对 amqplib
放在胡萝卜
中。
I just added timeout support for amqplib
in carrot
.
这是 amqplib.client0_8.Connection
:
http://github.com/ask/carrot/blob/master/carrot/backends/pyamqplib.py#L19-97
wait_multi
是 channel.wait $ c $的版本c>能够接收任意数量的
个频道。
wait_multi
is a version of channel.wait
able to receive on an arbitrary number
of channels.
我想这可能会在上游合并
I guess this could be merged upstream at some point.
这篇关于等待一个RabbitMQ消息超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!