Wednesday, June 15, 2011

AMQP PHP for RabbitMQ to talk to Node.js

There are really no examples on how to use PHP's AMQP PECL module, yet the documentation at is still great and easy to understand. So, after reading the documentation in 5 mins I was able to put together a PHP Producer and reuse my Node.js Consumer.

Here is an example starting with PHP
// connect
$cnn = new AMQPConnection();

// exchanges talk to queues set a fanout up
$ex = new AMQPExchange($cnn);
$ex->declare('notifExchange2', AMQP_EX_TYPE_FANOUT, AMQP_AUTODELETE);

// add stuff to a queue for me to look at later (not needed)
$queue = new AMQPQueue( $cnn );
$queue->bind('notifExchange2', 'routingkey');

// pure strings with no format are boring let's use json
$data =  array('message' => "helloworld");
$str = json_encode($data);

$ex->publish($str, 'routingKeyWhichIgnoredBecauseOfFanout', 0, array('Content-type' => 'text/json'));

Now for Node.js

#!/bin/env node


connection.addListener('ready', function () {
    var e ='notifExchange2', {type: 'fanout'});
    var q = connection.queue('100224', {autoDelete: false});

    q.on('queueDeclareOk', function (args) {
        puts('queue opened: Message Count:'+ args.messageCount + " ConsumerCount: " + args.consumerCount);
        q.bind(e, "#");
        q.subscribe(function(message) {
            puts("Got a message: " + var_dump(message));

Pretty straight forward. When the connection is ready setup the exchange, declare the queue, once the queue is declared bind it to the exchange and on q.subscribe var_dump the message out. Notice var_dump in javscript that's defined in utilities.


No comments: