python使用stomp连接activemq

2018-07-20 05:58:48来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

一、安装ActiveMQ服务

1. 当使用windows时,安装参考:https://blog.csdn.net/WuLex/article/details/78323811

    启动:运行activemq.bat

2. 当使用linux时,安装参考:https://www.cnblogs.com/andylhc/p/9337628.html

    启动:./activemq start

 

二、python使用stomp连接activemq

安装模块:pip3 install stomp.py  (注意是python3)

Python脚本如下:

# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 09:54:08 2018

@author: lihc
"""

# -*-coding:utf-8-*-
import stomp
import time
 
 
queue_name = '/queue/SampleQueue'
topic_name = '/topic/SampleTopic'
listener_name = 'SampleListener'
post=61613

class SampleListener(object):
    def on_message(self, headers, message):
        print ('headers: %s' % headers)
        print ('message: %s' % message)
 
# 推送到队列queue
def send_to_queue(msg):
    conn = stomp.Connection10([('127.0.0.1',post)])
    conn.start()
    conn.connect()
    conn.send(queue_name, msg)
    conn.disconnect()
 
#推送到主题
def send_to_topic(msg):
    conn = stomp.Connection10([('127.0.0.1',post)])
    conn.start()
    conn.connect()
    conn.send(topic_name, msg)
    conn.disconnect()
 
##从队列接收消息
def receive_from_queue():
    conn = stomp.Connection10([('127.0.0.1',61613)])
    conn.set_listener(listener_name, SampleListener())
    conn.start()
    conn.connect()
    conn.subscribe(queue_name)
    time.sleep(1) # secs
    conn.disconnect()
 
##从主题接收消息
def receive_from_topic():
    conn = stomp.Connection10([('127.0.0.1',post)])
    conn.set_listener(listener_name, SampleListener())
    conn.start()
    conn.connect()
    conn.subscribe(topic_name)
    while 1:
        send_to_topic('topic')
        time.sleep(3) # secs
    conn.disconnect()
 
if __name__=='__main__':
    send_to_queue('len 123')
    receive_from_queue()
    # send_to_topic('len 345')
    # receive_from_topic()

 

原文:https://blog.csdn.net/five3/article/details/79569587

另外参考:http://www.cnblogs.com/GarfieldTom/p/4153957.html

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Python学习笔记【第九篇】:Python面向对象基础

下一篇:Python学习笔记【第十篇】:Python面向对象进阶