利用python收发MQ
一、收发MQ基础
引入stomp包,
# -*- coding: utf-8 -*-
import stomp
import time,random
from cmd.util import timePaser
port = 700
ip='10.13.69.16'
passcode='8JiPUndN'
queue_name = '/topic/SampleQueue'
topic_name = '/topic/cweb.topic.receive.msg'
listener_name = 'SampleListener'
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([(ip, port)])
conn.start()
conn.connect()
conn.send(queue_name, msg)
conn.disconnect()
# 推送到主题
def send_to_topic(msg):
headers = {'type': 'bytesMessage'}
conn = stomp.Connection([(ip, port)])
conn.start()
conn.connect(username='admin', passcode=passcode, wait=True, )
conn.send(destination=topic_name, body=msg, headers=headers) # 发送消息
# print ("$$$ send one message")
conn.disconnect()
##从队列接收消息
def receive_from_queue():
conn = stomp.Connection10([(ip, port)])
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.Connection([(ip, port)])
conn.set_listener(listener_name, SampleListener())
conn.start()
conn.connect(username='admin', passcode=passcode, wait=True, headers={'tcpNoDelay': 'true'})
conn.subscribe(topic_name,id="", ack='auto')
while 1:
# send_to_topic('topic')
time.sleep(3) # secs
conn.disconnect()```
二、构造随机报文
```python
def sendTodoRand():
for i in range(1,3):
randomId=str(random.randrange(1000,9999));msgId=randomId+str(time.time())
msg = '''{"msgId":"''' \
+msgId+ '''","msgStatus":"'''+str(random.randrange(1,4))+'''","msgTitle":"待办事项标题'''\
+randomId+'''","msgTime":"'''+timePaser.nowTime()+'''","extendStr":{"showFlag":1,"picUrl":"","extendJson":"{\\\"extend1\\\":\\\"人数:100\\\"}","extendNoShow":""}}]}}
'''
print(msgId);print(msg)
send_to_topic(msg)```

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)