Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RabbitMQ - How to check if queue is empty?

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;
like image 801
Ahmed Khalaf Avatar asked Jan 07 '23 14:01

Ahmed Khalaf


1 Answers

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

like image 169
Arno Avatar answered Jan 19 '23 06:01

Arno