This topic describes the sample code for sending and receiving messages by using Apache RocketMQ 5.x SDK for C#.
Prerequisites
Before you begin, make sure that you have:
An ApsaraMQ for RocketMQ instance with an endpoint obtained. For more information, see Obtain the endpoint of an instance
A topic and a consumer group created on the instance
A C# development environment prepared. For more information, see Environment preparation
(Conditional) The instance username and password obtained, if you access the instance over the Internet or if the instance is a serverless instance with authentication-free in VPCs disabled
Sample code overview
Parameters
Replace the following placeholders in all sample code with your actual values:
| 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 the ApsaraMQ for RocketMQ instance. |
topic | normal_test | The topic to which messages are sent or from which messages are consumed. Create the topic on the instance in advance. For more information, see Create a topic. |
consumerGroup | GID_test | The consumer group for consuming messages. Create the consumer group on the instance in advance. For more information, see Create a consumer group. |
AccessKey | 1XVg0hzgKm****** | The instance username. Required for Internet access. For VPC access, required only when 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 instance password. Required under the same conditions as |
Access serverless instances over the Internet
To access a serverless ApsaraMQ for RocketMQ instance over the Internet, add SetNamespace to the client configuration and set it to your instance ID:
Replace InstanceId with your actual instance ID.
var clientConfig = new ClientConfig.Builder()
.SetEndpoints(endpoints)
.SetNamespace("<your-instance-id>") // Replace with your actual instance ID, for example, rmq-cn-xxx.
.SetCredentialsProvider(credentialsProvider)
.Build();