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. ?> 
相關文章
相關標籤/搜索