Andrew
Andrew

Reputation: 2114

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:

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);
    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?

Upvotes: 0

Views: 4084

Answers (2)

NeuroScr
NeuroScr

Reputation: 322

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

Upvotes: 0

Robin
Robin

Reputation: 4260

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.

Upvotes: 2

Related Questions