All Products
Search
Document Center

ApsaraMQ for RocketMQ:Sample code

Last Updated:Mar 14, 2025

This topic describes the sample code for sending and receiving messages by using Apache RocketMQ 5.x SDK for Python.

Message type

Sample code for sending messages

Sample code for receiving messages

Normal messages

simple_consumer_example.py

Transactional messages

transaction_producer_example.py

Parameters

Parameter

Example

Description

endpoints

rmq-cn-xxx.{regionId}.rmq.aliyuncs.com:8080

The endpoint of the ApsaraMQ for RocketMQ instance. For information about how to obtain the endpoint, see Obtain the endpoint of an instance.

  • If you access the instance over the Internet, specify the public endpoint.

  • If you access the instance in a VPC, specify the VPC endpoint.

InstanceId

rmq-cn-xxx

The ID of the ApsaraMQ for RocketMQ instance.

topic

normal_test

The topic to which messages are sent or from which messages are consumed in the ApsaraMQ for RocketMQ instance.

You must create the topic on the ApsaraMQ for RocketMQ instance in advance. For more information, see Create a topic.

consumer-group

GID_test

The consumer group that is used by consumers to consume messages in the ApsaraMQ for RocketMQ instance.

You must create the consumer group on the ApsaraMQ for RocketMQ instance in advance. For more information, see Create a consumer group.

ak

1XVg0hzgKm******

The username of the ApsaraMQ for RocketMQ instance. If you access the instance over the Internet, you must specify the username. If you access the instance in a VPC, you need to specify the username only if the instance is a serverless instance and the authentication-free in VPCs feature is disabled for the instance.

For information about how to obtain the username, see Obtain the username and password of an instance.

sk

ijSt8rEc45******

The password of the ApsaraMQ for RocketMQ instance. If you access the instance over the Internet, you must specify the password. If you access the instance in a VPC, you need to specify the password only if the instance is a serverless instance and the authentication-free in VPCs feature is disabled for the instance.

For information about how to obtain the password, see Obtain the username and password of an instance.

Description for accessing serverless instances over the Internet

If you access a serverless ApsaraMQ for RocketMQ instance over the Internet to send and receive messages, you must add the following information in the messaging code:

Note

Replace InstanceId with the ID of your ApsaraMQ for RocketMQ instance.

config = ClientConfiguration(endpoints, credentials, "InstanceId")

References