RabbitMQ - How to check if queue is empty?

Ahmed Khalaf picture Ahmed Khalaf · Sep 8, 2015 · Viewed 12k times · Source

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;

Answer

Arno picture Arno · Sep 6, 2017

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