我有一个抽象 RabbitMQ 服务器的 Web 服务接口(interface)(不要问我为什么,我知道这是一个不必要的步骤,但我必须这样做)。也就是说,我通过 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;
最佳答案
如果要获取队列的大小,可以使用php-amqlib调用queue_declare
,返回的第二个参数是队列中的消息数。
list($queue, $messageCount, $consumerCount) = $channel->queue_declare(QUEUE_NAME, true);
调用 queue_declare() 方法时,将 $passive 参数设置为 true 很重要
关于php - RabbitMQ - 如何检查队列是否为空?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32460212/