利用python收發MQ

木头左發表於2024-04-20

一、收發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)

相關文章