tencent cloud

TDMQ for RocketMQ

Release Notes and Announcements
Release Notes
Announcements
Product Introduction
Introduction and Selection of the TDMQ Product Series
What Is TDMQ for RocketMQ
Strengths
Scenarios
Product Series
Comparison with Open-Source RocketMQ
High Availability
Quotas and Limits
Supported Regions
Basic Concepts
Billing
Billing Overview
Pricing
Billing Examples
Pay-as-you-go Switch to Monthly Subscription (5.x)
Renewal
Viewing Consumption Details
Refund
Overdue Payments
Getting Started
Getting Started Guide
Preparations
Step 1: Creating TDMQ for RocketMQ Resources
Step 2: Using the SDK to Send and Receive Messages (Recommended)
Step 2: Running the TDMQ for RocketMQ Client (Optional)
Step 3: Querying Messages
Step 4: Deleting Resources
User Guide
Usage Process Guide
Configuring Account Permissions
Creating the Cluster
Configuring the Namespace
Configuring the Topic
Configuring the Group
Connecting to the Cluster
Managing Messages
Managing the Cluster
Viewing Monitoring Data and Configuring Alarms
Cross-Cluster Message Replication
Use Cases
Naming Conventions for Common Concepts of TDMQ for RocketMQ
RocketMQ Client Use Cases
RocketMQ Performance Load Testing and Capacity Assessment
Access over HTTP
Client Risk Descriptions and Update Guide
Migration Guide for TencentCloud API Operations Related to RocketMQ 4.x Cluster Roles
Migration Guide
Disruptive Migration
Seamless Migration
Developer Guide
Message Types
Message Filtering
Message Retries
POP Consumption Mode (5.x)
Clustering Consumption and Broadcasting Consumption
Subscription Relationship Consistency
Traffic Throttling
​​API Reference(5.x)
History
API Category
Making API Requests
Topic APIs
Consumer Group APIs
Message APIs
Role Authentication APIs
Hitless Migration APIs
Cloud Migration APIs
Cluster APIs
Data Types
Error Codes
​​API Reference(4.x)
SDK Reference
SDK Overview
5.x SDK
4.x SDK
Security and Compliance
Permission Management
CloudAudit
Deletion Protection
FAQs
4.x Instance FAQs
Agreements
TDMQ for RocketMQ Service Level Agreement
Contact Us

Using the C# SDK

PDF
Mode fokus
Ukuran font
Terakhir diperbarui: 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.


Bantuan dan Dukungan

Apakah halaman ini membantu?

masukan