我有下一个代码:
<?php
// callback function for recive the message and canceling consumer
function consumer(\AMQPEnvelope $envelope, \AMQPQueue $queue)
{
$queue->ack($envelope->getDeliveryTag());
$queue->cancel($envelope->getCorrelationId());
echo "Message was recived and consumer will be canceled by consumer tag: {$envelope->getCorrelationId()}\n";
}
// generating uniqie exchange and queue
$correlationId = uniqid(str_replace('.', '', (string)microtime(TRUE)) . '_');
$queueName = "databus_response_{$correlationId}";
$consumerTag = "consumer_tag_{$correlationId}";
// establesh connection
$connection = new \AMQPConnection(array('host'=>'127.0.0.1', 'user'=>'guest', 'password'=>'guest'));
$connection->connect();
$channel = new \AMQPChannel($connection);
// declare exchange
$exchange = new \AMQPExchange($channel);
$exchange->setFlags(AMQP_AUTODELETE);
$exchange->setType(AMQP_EX_TYPE_TOPIC);
$exchange->setName($queueName);
$exchange->declareExchange();
// declare queue
$queue = new \AMQPQueue($channel);
$queue->setFlags(AMQP_EXCLUSIVE);
$queue->setName($queueName);
$queue->declareQueue();
$queue->bind($queueName, '#');
// publish message in exchange
$exchange->publish('Test message', NULL, AMQP_PASSIVE, array('correlation_id' => $consumerTag));
// run consumer for getting this echange and canceling consumer after recive the message
$queue->consume('consumer', AMQP_NOWAIT, $consumerTag);
如何查看,我将一条消息发送到队列,并在此队列上运行使用者。在消费者方法中,您可以看到,我希望在通过&#34;取消&#34;方法,但消费者没有停止。我做错了什么?
答案 0 :(得分:3)
当您想要停止消费时,只需从消费者回调中返回false
。
来自AMQPQueue.php存根文件:
AMQPQueue :: consume()不会将处理线程返回给 PHP脚本,直到回调函数返回FALSE。
PS:伤心地说,php-amqp
扩展仍然缺乏良好的文档,但你可以随时阅读方法的注释中的存根文件或读到这里对波兰语言PHP官方网站有点过时文档 - {{3} (别担心,没人翻译,所以所有敏感文件都是英文)。
答案 1 :(得分:0)
现在,在php-amqplib v2。*世界中,您还可以在AMQPChannel对象上调用basic_cancel。
这是一个很好的blog post关于使用这种技术控制消费者数量和他们的ttl。