我有一个抽象 RabbitMQ 服务器的 Web 服务接口(不要问我为什么,我知道这是不必要的步骤,但我必须这样做)。也就是说,我通过 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;