python使用stomp连接activemq

一、安装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

posted on 2018-07-19 19:41  andy_1  阅读(8441)  评论(1编辑  收藏  举报

导航