RabbitMQ - How to check if queue is empty?

本小妞迷上赌 提交于 2020-01-04 17:08:31

问题


I have a web service interface that abstracts a RabbitMQ server (don't ask me why, I know it's an unnecessary step, but I have to). That is, I poll messages from the queue through a web service call, not directly over amqp.

Consuming via basic.consumer blocks the execution thread till there are messages in the queue. This makes the web service not return.

Code for illustration:

    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
    $channel = $connection->channel();

    $channel->queue_declare(QUEUE_NAME, false, true, false, false);
    $ret = array('body' => '');

    $callback = function($msg) use ($channel, &$ret) {
        $ret['body'] = $msg->body;
        /*
        Here I would basic.cancel the consumer if there were no messages in the queue
        */
    };

    $channel->basic_consume(QUEUE_NAME, 'tag', false, true, false, false, $callback);

    if (count($channel->callbacks)) {
        $channel->wait(); // blocks here...
    }

    return $ret;

回答1:


If you want to get the size of queue, you can call queue_declare with php-amqlib, the second argument of return is the number of messages in the queue.

  list($queue, $messageCount, $consumerCount) = $channel->queue_declare(QUEUE_NAME, true);

It is important to give the $passive argument to true when you call the queue_declare() method




回答2:


What I wanted to do is achieved by basic.get.

In php-amqlib:

$channel->basic_get(QUEUE_NAME, true); // the second arg is no_ack.

The second argument marks that no acknowledgment is expected for that message. That is, you don't have to "flag" the message as read for RabbitMQ to confidently dequeue it. Excluding it (having it = false) results in not popping the top message.

Why all this hassle?

I was wrapping the RabbitMQ code inside an http web service. And this is a not good idea (at least for my use case). As when the web service returns, and thus the rabbitmq connection terminates, the non (yet) acknowledged message is requeued back to the queue. So, if you have to adopt an http wrapper, make sure you isolate the lifetime of the rabbitmq connection from the http request lieftime. However, I didn't try this.



来源:https://stackoverflow.com/questions/32460212/rabbitmq-how-to-check-if-queue-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!