tencent cloud

TDMQ for RocketMQ

C++ SDK

PDF
포커스 모드
폰트 크기
마지막 업데이트 시간: 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.

Operation Steps

1. Prepare the environment.
1.1 Install the RocketMQ-Client-CPP library in the client environment. You can install the CPP dynamic library based on the official documentation. It is recommended that it be built from the master branch.
1.2 Import the RocketMQ-Client-CPP related header files and dynamic libraries into the project.
2. Initialize the message producer.
// Set the producer group name.
DefaultMQProducer producer(groupName);
// Set the service access address.
producer.setNamesrvAddr(nameserver);
// Set user permissions.
producer.setSessionCredentials(
accessKey, // Role token.
secretKey, // Role name.
"");
// Set the namespace (full name of the namespace).
producer.setNameSpace(namespace);
// Ensure that all parameters are set before startup.
producer.start();
Note:
You can log in to the TDMQ for RocketMQ console to obtain the following parameters.
Parameter
Description
groupName
Producer group name. You can copy the name from the Group Management page in the console.
nameserver
Cluster access address. You can obtain the access address from the Access Information module on the cluster basic information 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.
accessKey
Role token. You can copy the token from the AccessKey column on the Cluster Permissions page in the console.
nameSpace
Namespace name. You can copy the name from the Namespace page in the console. If you are using a 4.x general cluster or a 5.x cluster, specify the cluster ID for this parameter.
3. Send messages.
// Initialize the message content.
MQMessage msg(
topicName, // Topic name.
TAGS, // Message tag.
KEYS, // Message business key.
"Hello cpp client, this is a message." // Message content.
);
try {
// Send messages.
SendResult sendResult = producer.send(msg);
std::cout << "SendResult:" << sendResult.getSendStatus() << ", Message ID: " << sendResult.getMsgId()
<< std::endl;
} catch (MQException e) {
std::cout << "ErrorCode: " << e.GetError() << " Exception:" << e.what() << std::endl;
}
Parameter
Description
topicName
Topic name. You can copy the name from the Topic Management page in the console.
TAGS
Tags associated with the message.
KEYS
Sets the message business key.
4. Release resources.
// Release resources.
producer.shutdown();
5. Initialize the consumer.
// Message listening.
class ExampleMessageListener : public MessageListenerConcurrently {
public:
ConsumeStatus consumeMessage(const std::vector<MQMessageExt> &msgs) {
for (auto item = msgs.begin(); item != msgs.end(); item++) {
// Business.
std::cout << "Received Message Topic:" << item->getTopic() << ", MsgId:" << item->getMsgId() << ", TAGS:"
<< item->getTags() << ", KEYS:" << item->getKeys() << ", Body:" << item->getBody() << std::endl;
}
// If consumption is successful, return CONSUME_SUCCESS.
return CONSUME_SUCCESS;
// If consumption fails, return RECONSUME_LATER. The message will be consumed again.
// return RECONSUME_LATER;
}
};
// Initialize the consumer.
DefaultMQPushConsumer *consumer = new DefaultMQPushConsumer(groupName);
// Set the service address.
consumer->setNamesrvAddr(nameserver);
// Set user permissions.
consumer->setSessionCredentials(
accessKey,
secretKey,
"");
// Set the namespace.
consumer->setNameSpace(namespace);
// Set the instance name.
consumer->setInstanceName("CppClient");
// Register a custom listener function to handle received messages and return the processing result.
ExampleMessageListener *messageListener = new ExampleMessageListener();
// Subscribe to messages.
consumer->subscribe(topicName, TAGS);
// Set the message listener.
consumer->registerMessageListener(messageListener);
// After completing the preparations, you must call the startup function for the system to function properly.
consumer->start();
Note:
You can log in to the TDMQ for RocketMQ console to obtain the following parameters.
Parameter
Description
groupName
Consumer group name. You can copy the name from the Group Management page in the console.
nameserver
Cluster access address. You can obtain the access address from the Access Information module on the cluster basic information 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.
accessKey
Role token. You can copy the token from the AccessKey column on the Cluster Permissions page in the console.
namespace
Namespace name. You can copy the name from the Namespace page in the console.
topicName
Topic name. You can copy the name from the Topic Management page in the console.
TAGS
Used to set the tag for subscribed messages.
6. Release resources.
// Release resources.
consumer->shutdown();
7. View consumption 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.
If you need to send any delayed messages, set the __STARTDELIVERTIME property.
MQMessage msg("console topic", "tag", "Delay Message.");
chrono::system_clock::duration d = chrono::system_clock::now().time_since_epoch();
chrono::milliseconds mil = chrono::duration_cast<chrono::milliseconds>(d);
// Scheduled delayed message, in milliseconds, indicating that messages are delivered at the specified timestamp (after the current time).
// Set the time for delayed or scheduled delivery, for example, delivered 30 seconds after the current time.
long expectTime = mil.count() + 30000;
msg.setProperty("__STARTDELIVERTIME", to_string(expectTime));
Note:
The above is a brief introduction to message publishing and subscription. For details, see Demo or TDMQ for RocketMQ Official Documentation.


도움말 및 지원

문제 해결에 도움이 되었나요?

피드백