15 May 2012

RabbitMQ PHP in Ubuntu 12.04

Testing RabbitMQ PHP in Ubuntu 12.04
Examples for AMQP in official PHP site (last check 2012/05/15) not sync with API for PECL 1.0.1.
This is my version to test simple php amqp

emit_log.php:

// Create a connection
$cnn = new AMQPConnection(array('login'=>'guest', 'password'=>'abc123'));
$cnn->connect();

// Create a channel
$ch = new AMQPChannel($cnn);

// Declare a new exchange
$ex = new AMQPExchange($ch);
$ex->setName('logs');
$ex->setType(AMQP_EX_TYPE_FANOUT);
$ex->declare();

// Publish a message to the exchange with a routing key
$message = isset($argv[1]) ? $argv[1] : 'hello world message';
$ex->publish($message, 'routing.key');

receive_log.php:

// Create a connection
$cnn = new AMQPConnection(array('login'=>'guest', 'password'=>'abc123'));
$cnn->connect();


// Create a channel
$ch = new AMQPChannel($cnn);


// Declare a new exchange
$ex = new AMQPExchange($ch);
$ex->setName('logs');
$ex->setType(AMQP_EX_TYPE_FANOUT);


// Create a new queue
$q = new AMQPQueue($ch);
$q->declare();
$q->bind('logs', 'routing.key');


function cb($env, $q) {
    print $env->getBody()."\n";
}
// Read from the queue
$msg = $q->consume('cb');


Easier to manage rabbitmsq server with the rabbitmq_management than the rabbitmqctl
Example based on rabbitmq Publish/Subscribe tutorial
Post a Comment