Thursday, September 12, 2013

ActiveMQ with PHP

First you need to download and configure ActiveMQ, You can find latest ActiveMQ release from[1].

Download latest release from http://www.apache.org/dyn/closer.cgi?path=/activemq/apache-activemq/5.8.0/apache-activemq-5.8.0-bin.tar.gz


Step1 : svn co http://svn.apache.org/repos/asf/activemq/tags/activemq-x.x.x

At the date of writing this post , ActiveMQ 5.8.0 is the latest release. So here after lets replace x.x.x with 5.8.0.


Step 2 : go to the activemq directory cd activemq-5.8.0/

Step 3 : Run mvn clean install to build ActiveMQ from source. This step will take a while.

Step 4 :  Edit <ACTIVEMQ_HOME>/conf/activemq.xml and add following transport connector.

 <transportConnector name="stomp" uri="stomp://localhost:61613"/>
Step5 : Start ActiveMQ: <ACTIVEMQ_HOME>/bin/activemq console
Step6 : Install PHP stomp extension pear install stomp.If you don't have pear package installed, run sudo apt-get install php-pear first.

Lets move to the PHP side now, we need to write two snippets one to publish messages another one to subscribe previously published messages.

First the publisher, create publisher.php inside /var/www/activemqsample/ directory with following content.

<?php
$queue  = 'ActiveMQ';
$msg    = 'ActiveMQ with PHP';

try {
    $stomp = new Stomp('tcp://localhost:61613');
    while (true) {
      $stomp->send($queue, $msg);
      sleep(1);
    }
} catch(StompException $e) {
    die('Connection error: '.$e));
}
?>
 Then the subscriber, create subscriber.php inside /var/www/activemqsample/ directory with following content.
<?php
$queue  = 'ActiveMQ';

try {
    $stomp = new Stomp('tcp://localhost:61613');
    $stomp->subscribe($queue);
    while (true) {
       if ($stomp->hasFrame()) {
           $frame = $stomp->readFrame();
           if ($frame != NULL) {
               print "Received: ".$frame->body;
               $stomp->ack($frame);
           }
       }

    }
} catch(StompException $e) {
    die('Connection error: ' . $e);
}
?>
Now you can test the sample php application by running,
php publisher.php and php subscriber.php within /var/www/activemqsample/ directory.


[1] http://activemq.apache.org/download.html

2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete