等待带有超时的单个 RabbitMQ 消息 [英] Wait for a single RabbitMQ message with a timeout

查看:36
本文介绍了等待带有超时的单个 RabbitMQ 消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向 RabbitMQ 服务器发送一条消息,然后等待回复消息(在回复"队列中).当然,如果处理这些消息的应用程序关闭,我不想永远等待 - 需要超时.这听起来像是一项非常基本的任务,但我找不到办法做到这一点.我现在遇到了 py-amqplibRabbitMQ .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_getsleep 进行轮询,但这非常难看:

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)

当然有更好的方法吗?

推荐答案

我刚刚在 carrot 中添加了对 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 版本频道.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆