How on PHP cancel consumer in RabbitMQ?

command-line-interface, message-queue, php, rabbitmq

Solution

just return `false` from consumer callback when you want to stop consuming.

From AMQPQueue.php stub file:

The AMQPQueue::consume() will not return the processing thread back to the PHP script until the callback function returns FALSE.

P.S.: sad to say that `php-amqp` extension still lack of good documentation, but you can always read method annotation in stub files or read a bit outdated documentation on official php site in Polish language here - http://www.php.net/manual/pl/book.amqp.php (don't worry, nobody translated it, so all sensitive doc is in English).

Problem

I have next code: ``` <?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); ``` How you can see, i send one message to queue, and run consumer on this queue. In consumer method, you can see, what i want stop consumer on this queue after reciving first message by "cancel" method, but consumer not stopped. What i do wrong? - AMQP PECL module version 1.2.0 from https://github.com/pdezwart/php-amqp/tree/v1.2.0 - PHP 5.4.4-14+deb7u10 (cli) - Linux v270 3.2.0-4-amd64 #1 SMP Debian 3.2.54-2 x86_64 GNU/Linux

Original source