tencent cloud

TDMQ for RocketMQ

Using the C# SDK

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2026-01-23 17:52:24

Scenarios

This document uses the C# SDK as an example to describe how to send and receive messages through an open-source software development kit (SDK), helping you better understand the complete process of sending and receiving messages.

Prerequisites

You have obtained the client connection parameters as instructed in SDK Overview.
You have installed the DotNet environment.

Operation Steps

Step 1: Installing the RocketMQ5 SDK Dependency Library

Introduce related dependencies into the C# project using the following command:
dotnet add package RocketMQ.Client --version 5.2.0-rc1

Step 2: Producing Messages

using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Org.Apache.Rocketmq;
namespace examples
{
internal static class ProducerNormalMessageDemo
{
static readonly ILoggerFactory factory = LoggerFactory.Create(builder => builder.AddConsole());
static ILogger logger = factory.CreateLogger("Program_Producer");
internal static async Task QuickStart()
{
// Enable the switch if you use .NET Core 3.1 and want to disable TLS/SSL.
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
const string accessKey = "yourAccessKey";
const string secretKey = "yourSecretKey";
// Credential provider is optional for client configuration.
var credentialsProvider = new StaticSessionCredentialsProvider(accessKey, secretKey);
const string endpoints = "Tencent Cloud official website access address:8080";
var clientConfig = new ClientConfig.Builder()
.SetEndpoints(endpoints)
.SetCredentialsProvider(credentialsProvider)
.Build();
const string topic = "topicName";
// In most case, you don't need to create too many producers, single pattern is recommended.
// Producer here will be closed automatically.
var producer = await new Producer.Builder()
// Set the topic name(s), which is optional but recommended.
// It makes producer could prefetch the topic route before message publishing.
.SetTopics(topic)
.SetClientConfig(clientConfig)
.Build();
// Define your message body.
var bytes = Encoding.UTF8.GetBytes("foobar");
const string tag = "yourMessageTagA";
var message = new Message.Builder()
.SetTopic(topic)
.SetBody(bytes)
.SetTag(tag)
// You could set multiple keys for the single message actually.
.SetKeys("yourMessageKey-7044358f98fc")
.Build();
var sendReceipt = await producer.Send(message);
logger.LogInformation($"Send message successfully, messageId={sendReceipt.MessageId}");
// Close the producer if you don't need it anymore.
await producer.DisposeAsync();
}
}
}
Parameter
Description
accessKey
Role token. You can copy the token from the AccessKey column on the Cluster Permissions page in the console.
secretKey
Role name. You can copy the role name from the SecretKey column on the Cluster Permissions page in the console.
endpoints
Cluster access address. You can obtain the access address from the Access Information module on the Cluster Basic Information page in the console.
topic
Topic name. You can copy the name from the Topic Management page in the console.

Step 3: Consuming Messages

The TDMQ for RocketMQ 5.x series supports two consumption modes: Push Consumer and Simple Consumer.
Note:
The community edition C# SDK supports Push Consumer after version 5.2.0-rc1.
The following sample code uses Simple Consumer as an example. (When the message volume is particularly low, using single-threaded Simple Consumer may cause slight delays. If the message volume is small based on business evaluation, it is recommended that multi-threaded pulling be enabled or Push Consumer be used.)
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Org.Apache.Rocketmq;
namespace examples
{
internal static class SimpleConsumerExample
{
static readonly ILoggerFactory factory = LoggerFactory.Create(builder => builder.AddConsole());
static ILogger logger = factory.CreateLogger("Program_Consumer");
internal static async Task QuickStart()
{
// Enable the switch if you use .NET Core 3.1 and want to disable TLS/SSL.
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
const string accessKey = "yourAccessKey";
const string secretKey = "yourSecretKey";
// Credential provider is optional for client configuration.
var credentialsProvider = new StaticSessionCredentialsProvider(accessKey, secretKey);
const string endpoints = "rmq-xxx.rocketmq.gz.qcloud.tencenttdmq.com:8080"; // Tencent Cloud access point.
var clientConfig = new ClientConfig.Builder()
.SetEndpoints(endpoints)
.SetCredentialsProvider(credentialsProvider)
.Build();
// Add your subscriptions.
const string consumerGroup = "yourConsumerGroup";
const string topic = "yourTopic";
var subscription = new Dictionary<string, FilterExpression>
{ { topic, new FilterExpression("*") } };
// In most case, you don't need to create too many consumers, single pattern is recommended.
var simpleConsumer = await new SimpleConsumer.Builder()
.SetClientConfig(clientConfig)
.SetConsumerGroup(consumerGroup)
.SetAwaitDuration(TimeSpan.FromSeconds(15))
.SetSubscriptionExpression(subscription)
.Build();
while (true)
{
var messageViews = await simpleConsumer.Receive(16, TimeSpan.FromSeconds(15));
foreach (var message in messageViews)
{
logger.LogInformation(
$"Received a message, topic={message.Topic}, message-id={message.MessageId}, body-size={message.Body.Length}");
await simpleConsumer.Ack(message);
logger.LogInformation($"Message is acknowledged successfully, message-id={message.MessageId}");
// await simpleConsumer.ChangeInvisibleDuration(message, TimeSpan.FromSeconds(15));
// Logger.LogInformation($"Changing message invisible duration successfully, message=id={message.MessageId}");
}
}
// Close the simple consumer if you don't need it anymore.
// await simpleConsumer.DisposeAsync();
}
}
}
Push Consumer
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Org.Apache.Rocketmq;

namespace examples
{
public class PushConsumerExample
{
private static readonly ILogger Logger = MqLogManager.CreateLogger(typeof(PushConsumerExample).FullName);

private static readonly string Endpoint = Environment.GetEnvironmentVariable("ROCKETMQ_ENDPOINT");

internal static async Task QuickStart()
{
const string accessKey = "yourAccessKey";
const string secretKey = "yourSecretKey";
// Enable the switch if you use .NET Core 3.1 and want to disable TLS/SSL.
// AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

// Credential provider is optional for client configuration.
var credentialsProvider = new StaticSessionCredentialsProvider(accessKey, secretKey);
const string endpoints = "rmq-xxx.rocketmq.gz.qcloud.tencenttdmq.com:8080"; // Tencent Cloud access point.
var clientConfig = new ClientConfig.Builder()
.SetEndpoints(Endpoint)
.SetCredentialsProvider(credentialsProvider)
.Build();

// Add your subscriptions.
const string consumerGroup = "yourConsumerGroup";
const string topic = "yourTopic";
var subscription = new Dictionary<string, FilterExpression>
{ { topic, new FilterExpression("*") } };

var pushConsumer = await new PushConsumer.Builder()
.SetClientConfig(clientConfig)
.SetConsumerGroup(consumerGroup)
.SetSubscriptionExpression(subscription)
.SetMessageListener(new CustomMessageListener())
.Build();

Thread.Sleep(Timeout.Infinite);

// Close the push consumer if you don't need it anymore.
// await pushConsumer.DisposeAsync();
}

private class CustomMessageListener : IMessageListener
{
public ConsumeResult Consume(MessageView messageView)
{
// Handle the received message and return consume result.
Logger.LogInformation($"Consume message={messageView}");
return ConsumeResult.SUCCESS;
}
}
}
}
Parameter
Description
accessKey
Role token. You can copy the token from the AccessKey column on the Cluster Permissions page in the console.
secretKey
Role name. You can copy the role name from the SecretKey column on the Cluster Permissions page in the console.
endpoints
Cluster access address. You can obtain the access address from the Access Information module on the Cluster Basic Information page in the console.
consumerGroup
Consumer group name. You can copy the name from the Group Management page in the console.
topic
Topic name. You can copy the name from the Topic Management page in the console.

Step 4: Viewing Message Details

After a message is sent, you will receive a message ID (messageID). You can choose Message Query > General Query in the console to query the recently sent message, including the message details and trace.


Ajuda e Suporte

Esta página foi útil?

comentários