ActiveMQ這款開源消息服務器提供了多語言支持,除了通常的Java客戶端之外,還能夠使用C/C++、PHP、Python、JavaScript(Ajax)等語言開發客戶端。最近因爲項目須要,須要提供PHP和Python的主題訂閱客戶端。這裏做爲總結,列出這兩種語言客戶端的簡單安裝和使用。php
對於PHP和Python,能夠經過使用STOMP協議與消息服務器進行通信。在ActiveMQ的配置文件activemq.xml中,須要添加如下語句,來提供基於STOMP協議的鏈接器。服務器
- <transportConnectors>
- <transportConnector name="openwire" uri="tcp://0.0.0.0:61616"/>
- <transportConnector name="stomp" uri="stomp://0.0.0.0:61613"/><!--添加stomp鏈接器-->
- </transportConnectors>
Python
安裝Python27,並安裝stomppy(http://code.google.com/p/stomppy/)這一客戶端庫:tcp
基於stomppy訪問ActiveMQ的Python代碼:ide
- import time, sys
- import stomp
- #消息偵聽器
- class MyListener(object):
- def on_error(self, headers, message):
- print 'received an error %s' % message
- def on_message(self, headers, message):
- print '%s' % message
- #建立鏈接
- conn = stomp.Connection([('127.0.0.1',61613)])
- #設置消息偵聽器
- conn.set_listener('', MyListener())
- #啓動鏈接
- conn.start()
- conn.connect()
- #訂閱主題,並採用消息自動確認機制
- 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
- <?php
- $topic = '/topic/all_news';
- /* connection */
- try {
- $stomp = new Stomp('tcp://127.0.0.1:61613');
- } catch(StompException $e) {
- die('Connection failed: ' . $e->getMessage());
- }
- /* subscribe to messages from the queue 'foo' */
- $stomp->subscribe($topic);
- /* read a frame */
- while(true) {
- $frame = $stomp->readFrame();
- if ($frame != null) {
- echo $frame->body;
- /* acknowledge that the frame was received */
- $stomp->ack($frame);
- }
- }
- /* close connection */
- unset($stomp);
- ?>