本文提供使用 PYTHON SDK 收发延迟消息的示例代码供您参考。
发送延迟消息需要在控制台申请延迟消息类型的topic,rocketmq 5.x版本支持任意精度的延迟消息,发送延迟消息的示例代码如下。
import time from rocketmq import ClientConfiguration, Credentials, Message, Producer from datetime import datetime, timedelta if __name__ == '__main__': # 火山接入点 endpoints = "rocketmq-xxxx:8080" credentials = Credentials() # if auth enable, 火山ak,sk credentials = Credentials("xxxx", "xxxx") config = ClientConfiguration(endpoints, credentials) topic = "xxxx" # 延迟消息类型topic producer = Producer(config, (topic,)) try: producer.startup() try: msg = Message() msg.topic = topic msg.body = "hello, rocketmq.".encode('utf-8') msg.tag = "rocketmq-send-delay-message" msg.keys = "send_sync" # 延迟时间 msg.delivery_timestamp = int(time.mktime((datetime.now() + timedelta(seconds=30)).timetuple())) msg.add_property("send", "sync") res = producer.send(msg) print(f"{producer.__str__()} send message success. {res}") producer.shutdown() print(f"{producer.__str__()} shutdown.") except Exception as e: print(f"normal producer example raise exception: {e}") producer.shutdown() except Exception as e: print(f"{producer.__str__()} startup raise exception: {e}") producer.shutdown()
延迟消息的订阅方式与普通消息一致,示例代码如下所示。
from rocketmq import ClientConfiguration, Credentials, SimpleConsumer if __name__ == '__main__': # 火山接入点 endpoints = "rocketmq-xxxx:8080" credentials = Credentials() # if auth enable, 火山ak,sk credentials = Credentials("xxxx", "xxxx") config = ClientConfiguration(endpoints, credentials) topic = "xxxx" # topic名称 simple_consumer = SimpleConsumer(config, "groupName") # group name try: simple_consumer.startup() try: simple_consumer.subscribe(topic) # use tag filter # simple_consumer.subscribe(topic, FilterExpression("tag")) while True: try: messages = simple_consumer.receive(32, 15) if messages is not None: print(f"{simple_consumer.__str__()} receive {len(messages)} messages.") for msg in messages: simple_consumer.ack(msg) print(f"{simple_consumer.__str__()} ack message:[{msg.message_id}].") except Exception as e: print(f"receive or ack message raise exception: {e}") except Exception as e: print(f"{simple_consumer.__str__()} subscribe topic:{topic} raise exception: {e}") simple_consumer.shutdown() except Exception as e: print(f"{simple_consumer.__str__()} startup raise exception: {e}") simple_consumer.shutdown()