News Archive
PhpRiot Newsletter
Your Email Address:

More information

Exploring RabbitMQ and PHP

Note: This article was originally published at Planet PHP on 21 July 2011.
Planet PHP

I'm exploring the possibility of using RabbitMQ for an upcoming project. RabbitMQ is a free/open source message broker platform. It uses the open Advanced Message Queuing Protocol (AMQP) standard and is written in Erlang using the Open Telecom Platform (OTP). It promises a high level of availability, throughput, scalability, and portability. Since it is built using open standards, it is interoperable with other messaging systems and can be accessed from any platform.

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

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 rabbitmq-c $ cd rabbitmq-c $ hg clone 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.