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   andy_1  阅读(8463)  评论(1编辑  收藏  举报

编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示