1、参考源码
看源码,可以修改消息字节长度限制(rocketmq/client.py)
2、推送消息
from rocketmq.client import Producer, Message
producer = Producer('PID-001') #随便
producer.set_namesrv_addr('ip:port') #ip和端口
producer.start()
msg = Message('rocket_mq_test_broadcast_topic') #topic
msg.set_keys('2020-12-15')
msg.set_tags('explain')
msg.set_body('{"key":"value"}')
ret = producer.send_sync(msg)
print(ret.status, ret.msg_id, ret.offset)
producer.shutdown()
推送消息的时候,如果消息所占字节太长,需要手动设置size,代码中设置的是1M。
producer = Producer('PID-001',max_message_size=1024*1024)
3、消费方式PullConsumer(全部消费)(可重复消费)
from rocketmq.client import PullConsumer
import json
consumer = PullConsumer('PID-001')
consumer.set_namesrv_addr('ip:port')
consumer.start()
for msg in consumer.pull('rocket_mq_test_broadcast_topic'):
print(msg.tags)
print(msg.keys)
print(msg.id, msg.body)
print(msg.topic)
print(msg)
data=json.loads(str(msg)) #dict
consumer.shutdown()
4、消费方式PushConsumer(即时消费)(不可重复消费)
import time
from rocketmq.client import PushConsumer
def callback(msg):
print(msg)
consumer = PushConsumer('PID-001')
consumer.set_namesrv_addr('ip:port')
consumer.subscribe("rocket_mq_test_broadcast_topic",callback)
consumer.start()
while True:
time.sleep(30)
consumer.shutdown()