RabbitMQ - 如何检查队列是否为空?

Ahm*_*laf 2 php rabbitmq php-amqplib

我有一个Web服务接口抽象RabbitMQ服务器(不要问我为什么,我知道这是一个不必要的步骤,但我必须).也就是说,我通过Web服务调用从队列中轮询消息,而不是直接通过amqp.

通过basic.consumer块消耗执行线程直到队列中有消息.这使得Web服务无法返回.

插图代码:

    $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;
Run Code Online (Sandbox Code Playgroud)

Arn*_*rno 6

如果你想获得队列的大小,你可以调用queue_declare用php-amqlib,回报第二个参数是队列中的消息的数量.

  list($queue, $messageCount, $consumerCount) = $channel->queue_declare(QUEUE_NAME, true);
Run Code Online (Sandbox Code Playgroud)

调用queue_declare()方法时,将$ passive参数设置为true非常重要