python使用stomp鏈接activemq

1、安裝ActiveMQ服務

1. 當使用windows時,安裝參考:https://blog.csdn.net/WuLex/article/details/78323811html

    啓動:運行activemq.batpython

2. 當使用linux時,安裝參考:https://www.cnblogs.com/andylhc/p/9337628.htmllinux

    啓動:./activemq startwindows

 

2、python使用stomp鏈接activemq

安裝模塊:pip3 install stomp.py  (注意是python3)post

Python腳本以下:spa

# -*- 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.net

另外參考:http://www.cnblogs.com/GarfieldTom/p/4153957.htmlcode

相關文章
相關標籤/搜索