ActiveMQ的PHP、Python客户端

ActiveMQ这款开源消息服务器提供了多语言支持,除了通常的Java客户端之外,还能够使用C/C++、PHP、Python、JavaScript(Ajax)等语言开发客户端。最近因为项目须要,须要提供PHP和Python的主题订阅客户端。这里做为总结,列出这两种语言客户端的简单安装和使用。php

对于PHP和Python,能够经过使用STOMP协议与消息服务器进行通信。在ActiveMQ的配置文件activemq.xml中,须要添加如下语句,来提供基于STOMP协议的链接器。服务器

  
  
  
  
  1. <transportConnectors> 
  2.     <transportConnector name="openwire" uri="tcp://0.0.0.0:61616"/> 
  3.     <transportConnector name="stomp" uri="stomp://0.0.0.0:61613"/><!--添加stomp链接器--> 
  4. </transportConnectors> 

Python
安装Python27,并安装stomppy(http://code.google.com/p/stomppy/)这一客户端库:tcp

基于stomppy访问ActiveMQ的Python代码:ide

  
  
  
  
  1. import time, sys 
  2. import stomp 
  3.  
  4. #消息侦听器 
  5. class MyListener(object): 
  6.     def on_error(self, headers, message): 
  7.         print 'received an error %s' % message 
  8.  
  9.     def on_message(self, headers, message): 
  10.         print '%s' % message 
  11.          
  12. #建立链接 
  13. conn = stomp.Connection([('127.0.0.1',61613)]) 
  14.  
  15. #设置消息侦听器 
  16. conn.set_listener('', MyListener()) 
  17.  
  18. #启动链接 
  19. conn.start() 
  20. conn.connect() 
  21.  
  22. #订阅主题,并采用消息自动确认机制 
  23. conn.subscribe(destination='/topic/all_news', ack='auto'

PHPgoogle

安装PHP5,并安装STOMP的客户端库(http://php.net/manual/zh/book.stomp.php):spa

tar -zxf stomp-1.0.5.tgz
cd stomp-1.0.5/
/usr/local/php/bin/phpize
./configure --enable-stomp --with-php-config=/usr/local/php/bin/php-config
make
make install

安装完成后,将生成的stomp.so移入php.ini中指定的extension_dir目录下,并在php.ini中添加该客户端库:.net

extension=stomp.so

访问ActiveMQ的PHP代码:code

  
  
  
  
  1. <?php 
  2.  
  3. $topic  = '/topic/all_news'
  4.  
  5. /* connection */ 
  6. try { 
  7.     $stomp = new Stomp('tcp://127.0.0.1:61613'); 
  8. } catch(StompException $e) { 
  9.     die('Connection failed: ' . $e->getMessage()); 
  10.  
  11. /* subscribe to messages from the queue 'foo' */ 
  12. $stomp->subscribe($topic); 
  13.  
  14. /* read a frame */ 
  15. while(true) { 
  16.         $frame = $stomp->readFrame(); 
  17.          
  18.         if ($frame != null) { 
  19.             echo $frame->body; 
  20.  
  21.             /* acknowledge that the frame was received */ 
  22.             $stomp->ack($frame); 
  23.         } 
  24.  
  25. /* close connection */ 
  26. unset($stomp); 
  27.  
  28. ?>