zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Go语言基础之map
    Go语言基础之切片
    Go语言基础之数组
    Go语言fmt.Printf使用指南
    Go语言基础之流程控制
    Go语言基础之运算符
    Go语言基础之变量和常量
    Go语言环境搭建
    随笔
    使用SocketServer 创建TCP服务端
  • 原文地址:https://www.cnblogs.com/xiaochongzi/p/6484627.html
Copyright © 2011-2022 走看看