Search code examples
.netpythonrabbitmqamqppy-amqplib

Wait for a single RabbitMQ message with a timeout


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.

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)

Surely there is some better way?


Solution

  • I just added timeout support for amqplib in carrot.

    This is a subclass of amqplib.client0_8.Connection:

    http://github.com/ask/carrot/blob/master/carrot/backends/pyamqplib.py#L19-97

    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.