How do you synchronously listen for messages from a RabbitMQ queue in PHP?
I am using RabbitMQ to implement a worker task queue for a search indexer process using the PHP AMQP extension. I need the search indexer demon to listen for messages on the queue and consume them when it's available.
I see two methods for consuming content from a queue:
- AMQPQueue::get - doesn't block, so probably not what I'm after
- AMQPQueue::consume - seems promising
However, using consume appears to set up a consumer that is not then removed. Here's the PHP:
$opts = array('min' => 1, 'max' => 10, 'ack' => false);
$messages = array();
while (count($messages) or $messages = $q->consume($opts)) {
$msg = array_pop($messages);
开发者_StackOverflow var_dump($msg);
// ...Do work here...
$q->ack($msg['delivery_tag']);
}
And you can see the consumers building up using rabbitmqctl:
[andrew@localhost ~] rabbitmqctl list_queues name consumers
Listing queues ...
test_queue 3
[andrew@localhost ~] rabbitmqctl list_queues name consumers
Listing queues ...
test_queue 4
So the question is, what is the correct way to bind a PHP daemon to a queue such that it blocks while it waits for messages to be available, and starts blocking/listening again when it has completed the work associated with each message batch?
I'm not sure how the PHP Pecl extension implements consumers, but my Amqp library allows you to listen out for incoming messages (i.e. consume) by calling a function, and there are several "exit strategies" available in case you don't want to block forever. There's documentation available here, check the section "Implementing a Consumer", and a demo script here.
consume is what you want. It'll block until it receives a message.
The API has changed a big since your code, so it's hard to guess what went wrong.
http://www.php.net/manual/en/amqpqueue.consume.php
has the semi latest documentation and example
精彩评论