Python 版本:3.8.17
rocketmq-client-python 版本:2.0.1rc1 (自己下载的master分支下手动安装的)
代码:
def send_message(producer, body):
try:
message = Message("test")
message.set_body(json.dumps(body))
result = producer.send_sync(message)
print(f"生产者发送消息状态: {str(result.status)} 消息 ID: {result.msg_id}, offset: {result.offset}")
del result
except Exception as e:
print(f"生产者发送消息失败:{repr(e)}")
finally:
del message
gc.collect()
def producer():
ROCKETMQ_HOST = os.getenv("ROCKETMQ_HOST")
ROCKETMQ_PORT = os.getenv("ROCKETMQ_PORT")
ROCKETMQ_ACCESS_KEY = os.getenv("ROCKETMQ_ACCESS_KEY")
ROCKETMQ_ACCESS_SECRET = os.getenv("ROCKETMQ_ACCESS_SECRET")
producer = Producer('algo-producer')
producer.set_name_server_address(f"{ROCKETMQ_HOST}:{ROCKETMQ_PORT}")
producer.set_session_credentials(ROCKETMQ_ACCESS_KEY, ROCKETMQ_ACCESS_SECRET, "")
producer.start()
try:
while True:
body = {"a":'x'}
send_message(producer,json.dumps(body))
time.sleep(0.2)
except KeyboardInterrupt:
print("退出")
finally:
producer.shutdown()
if __name__ == '__main__':
producer()