python操作消息队列ActiveMQ案例

本文详细介绍了如何使用Python与ActiveMQ消息队列进行交互,包括连接配置、发送与接收消息等关键步骤,帮助开发者掌握在实际项目中应用ActiveMQ的基础技巧。
摘要由CSDN通过智能技术生成
import stomp
import time
import json
 
 
queue_name = '/queue/SampleQueue'
topic_name = '/topic/SampleTopic'
listener_name = 'SampleListener'
 
# class SampleListener(object):
#     def on_message(self, headers, message):
#         print ('headers: %s' % headers)
#         print ('message: %s' % message)

class SampleListener(stomp.ConnectionListener):
    def on_message(self, message):
        # print ('headers: %s' % headers)
        print ('message: %s' % message)
 
# 推送到队列queue
def send_to_queue(msg):
    conn = stomp.Connection10([('127.0.0.1',61613)])
    # conn.start()
    conn.connect()
    conn.send(queue_name, msg)
    conn.disconnect()
 
#推送到主题
def send_to_topic(msg):
    conn = stomp.Connection10([('127.0.0.1',61613)])
    # 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',61613)])
    conn.set_listener(listener_name, SampleListener())
    # conn.start()
    conn.connect()
    conn.subscribe(topic_name)
    while 1:
        data = json.dumps({'name':'zhangsan','age':12})
        send_to_topic(data)
        time.sleep(3) # secs
 
    conn.disconnect()
 
if __name__=='__main__':
    # send_to_queue('len 123')
    # receive_from_queue()
 
    receive_from_topic()

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值