All Products
Search
Document Center

ApsaraMQ for RocketMQ:Sample code for Go

Last Updated:Mar 11, 2026

Send and receive messages using the Apache RocketMQ 5.x SDK for Go. The following table lists sample code for each supported message type, along with the configuration parameters for connecting to your ApsaraMQ for RocketMQ instance.

Sample code by message type

All message types share a single SimpleConsumer implementation for receiving messages. The producer implementation varies by message type.

Message typeProducer sampleConsumer sample
Normal messagesSynchronous: ExampleProducerNormalMessage.goExampleSimpleConsumer.go
Normal messagesAsynchronous: AsyncExampleProducerNormalMessage.goSame as above
Ordered messagesExampleProducerWithFifoMessage.goSame as above
Scheduled and delayed messagesExampleProducerDelayMessage.goSame as above
Transactional messagesExampleProducerWithTransactionalMessage.goSame as above

Parameters

Replace the following placeholders in the sample code with values from your ApsaraMQ for RocketMQ instance.

ParameterExampleDescription
Endpointrmq-cn-xxx.{regionId}.rmq.aliyuncs.com:8080The instance endpoint. Use the public endpoint for Internet access or the VPC endpoint for VPC access. For more information, see Obtain the endpoint of an instance.
InstanceIdrmq-cn-xxxThe ID of your ApsaraMQ for RocketMQ instance.
Topicnormal_testThe topic for sending and consuming messages. Create the topic in advance. For more information, see Create a topic.
ConsumerGroupGID_testThe consumer group for consuming messages. Create the consumer group in advance. For more information, see Create a consumer group.
AccessKey1XVg0hzgKm******The username of the instance. Required for Internet access. For VPC access, required only if the instance is serverless and authentication-free in VPCs is disabled. For more information, see Obtain the username and password of an instance.
SecretKeyijSt8rEc45******The password of the instance. Required for Internet access. For VPC access, required only if the instance is serverless and authentication-free in VPCs is disabled. For more information, see Obtain the username and password of an instance.

Access a serverless instance over the Internet

To access a serverless ApsaraMQ for RocketMQ instance over the Internet, add the NameSpace and Credentials fields to the SDK configuration.

Note

Replace InstanceId with your actual instance ID.

Producer configuration

producer, err := rmq_client.NewProducer(&rmq_client.Config{
	Endpoint: Endpoint,
	NameSpace: "InstanceId",
	Credentials: &credentials.SessionCredentials{
		AccessKey:    AccessKey,
		AccessSecret: SecretKey,
	},
},

Consumer configuration

simpleConsumer, err := rmq_client.NewSimpleConsumer(&rmq_client.Config{
	Endpoint: Endpoint,
	ConsumerGroup: ConsumerGroup,
	NameSpace: "InstanceId",
	Credentials: &credentials.SessionCredentials{
		AccessKey:    AccessKey,
		AccessSecret: SecretKey,
	},
},