Exploring RabbitMQ and PHP
I’ll be using RabbitMQ first from PHP, but I plan on using it to send and receive messages to and from other systems. Following are the steps I used to get RabbitMQ and PHP’s AMQP library setup on my development machine.
First, I installed RabbitMQ using MacPorts:
$ sudo port install rabbitmq-server
Then, I started RabbitMQ:
$ sudo rabbitmq-server -detached
Next, I installed the librabbitmq library using a slight variation of the instructions on PHP’s AMQP Installation page (you may need to install Mercurial first):
$ hg clone http://hg.rabbitmq.com/rabbitmq-c/rev/3c549bb09c16 rabbitmq-c $ cd rabbitmq-c $ hg clone http://hg.rabbitmq.com/rabbitmq-codegen/rev/f8b34141e6cb codegen $ autoreconf -i && ./configure && make && sudo make install
Then, I installed the AMQP extension using PECL:
$ sudo pecl install amqp-beta
To test that everything works, I opened up two interactive PHP shells using php -a. I ran the following code in the first PHP shell:
$exchangeName = 'messages'; $routeKey = 'routeA'; $message = 'Hello, world.'; $connection = new AMQPConnection(); $connection->connect(); $exchange = new AMQPExchange($connection); $exchange->declare($exchangeName);
I then ran the following code in the second PHP shell:
$exchangeName = 'messages'; $routeKey = 'routeA'; $connection = new AMQPConnection(); $connection->connect(); $queue = new AMQPQueue($connection); $queue->declare($exchangeName); $queue->bind($exchangeName, $routeKey);
Back in the first PHP shell:
$exchange->publish($message, $routeKey);
Back in the second PHP shell:
$message = $queue->get(); print_r($message);
Here is the output I got from the print_r statement:
Array
(
[routing_key] => routeA
[exchange] => messages
[delivery_tag] => 1
[Content-type] => text/plain
[count] => 0
[msg] => Hello, world.
)
There are several other options that can be set, and a lot more to learn about RabbitMQ and AMP. Check out the documentation for PHP’s AMQP extension for details about working with AMQP servers from PHP.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)



Comments
Nabeel Manara replied on Fri, 2012/01/27 - 12:30pm