利用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)```
![](https://mutouzuo.oss-cn-hangzhou.aliyuncs.com/my/mudouzuo1.png)