ActiveMQ的PHP、Python客戶端


ActiveMQ這款開源消息服務器提供了多語言支持,除了一般的Java客戶端以外,還可以使用C/C++、PHP、Python、JavaScript(Ajax)等語言開發客戶端。最近由於項目需要,需要提供PHP和Python的主題訂閱客戶端。這里作為總結,列出這兩種語言客戶端的簡單安裝和使用。

對於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/)這一客戶端庫:

基於stomppy訪問ActiveMQ的Python代碼:

  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') 

PHP

安裝PHP5,並安裝STOMP的客戶端庫(http://php.net/manual/zh/book.stomp.php):

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中添加該客戶端庫:

extension=stomp.so

訪問ActiveMQ的PHP代碼:

  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. ?> 

 

本文出自 “學習文檔” 博客,請務必保留此出處http://zephiruswt.blog.51cto.com/5193151/1109606


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM