Wait for a single RabbitMQ message with a timeout

后端 未结 5 1616
礼貌的吻别
礼貌的吻别 2020-12-15 12:53

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 applicatio

5条回答
  •  庸人自扰
    2020-12-15 13:18

    Here's what I ended up doing in the .NET client:

    protected byte[] WaitForMessageWithTimeout(string queueName, int timeoutMs)
    {
        var consumer = new QueueingBasicConsumer(Channel);
        var tag = Channel.BasicConsume(queueName, true, null, consumer);
        try
        {
            object result;
            if (!consumer.Queue.Dequeue(timeoutMs, out result))
                throw new ApplicationException(string.Format("Timeout ({0} seconds) expired while waiting for an MQ response.", timeoutMs / 1000.0));
    
            return ((BasicDeliverEventArgs)result).Body;
        }
        finally
        {
            Channel.BasicCancel(tag);
        }
    }
    

    Unfortunately, I cannot do the same with py-amqplib, because its basic_consume method does not call the callback unless you call channel.wait() and channel.wait() doesn't support timeouts! This silly limitation (which I keep running into) means that if you never receive another message your thread is frozen forever.

提交回复
热议问题