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 type | Producer sample | Consumer sample |
|---|---|---|
| Normal messages | Synchronous: ExampleProducerNormalMessage.go | ExampleSimpleConsumer.go |
| Normal messages | Asynchronous: AsyncExampleProducerNormalMessage.go | Same as above |
| Ordered messages | ExampleProducerWithFifoMessage.go | Same as above |
| Scheduled and delayed messages | ExampleProducerDelayMessage.go | Same as above |
| Transactional messages | ExampleProducerWithTransactionalMessage.go | Same as above |
Parameters
Replace the following placeholders in the sample code with values from your ApsaraMQ for RocketMQ instance.
| Parameter | Example | Description |
|---|---|---|
Endpoint | rmq-cn-xxx.{regionId}.rmq.aliyuncs.com:8080 | The 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. |
InstanceId | rmq-cn-xxx | The ID of your ApsaraMQ for RocketMQ instance. |
Topic | normal_test | The topic for sending and consuming messages. Create the topic in advance. For more information, see Create a topic. |
ConsumerGroup | GID_test | The consumer group for consuming messages. Create the consumer group in advance. For more information, see Create a consumer group. |
AccessKey | 1XVg0hzgKm****** | 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. |
SecretKey | ijSt8rEc45****** | 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,
},
},