本文提供使用 TCP 协议下的开源 C++ SDK 来收发事务消息的示例代码供您参考。

阿里云 RocketMQ 提供类似 X/Open XA 的分布式事务功能,通过阿里云 RocketMQ 事务消息,能达到分布式事务的最终一致。

交互流程

事务消息交互流程如下图所示。

process

详情请参见事务消息

前提条件

安装 CPP 动态库

发送事务消息

  1. 将以下代码拷贝到 TransProducerDemo.cpp 文件中,修改相应的参数后,使用 g++ 命令进行编译,生成可执行文件,即可直接运行。

    g++ -o trans_producer_demo -std=c++11 -lz -lrocketmq TransProducerDemo.cpp

  2. 发送事务消息的示例代码如下。
    #include <iostream>
    #include <chrono>
    #include <thread>
    #include "TransactionMQProducer.h"
    #include "MQClientException.h"
    #include "TransactionListener.h"
    
    using namespace std;
    using namespace rocketmq;
    
    class ExampleTransactionListener : public TransactionListener {
    public:
        LocalTransactionState executeLocalTransaction(const MQMessage &msg, void *arg) {
            //执行本地事务,成功返回 COMMIT_MESSAGE,失败返回 ROLLBACK_MESSAGE,不确定返回 UNKNOWN
            //如果返回 UNKNOWN,则会触发定时任务回查状态
            std::cout << "Execute Local Transaction,Received Message Topic:" << msg.getTopic() << ", MsgId:"
                      << msg.getBody() << std::endl;
            return UNKNOWN;
        }
    
        LocalTransactionState checkLocalTransaction(const MQMessageExt &msg) {
            //回查本地事务执行情况,成功返回 COMMIT_MESSAGE,失败返回 ROLLBACK_MESSAGE,不确定返回 UNKNOWN
            //如果返回 UNKNOWN,则等待下次定时任务回查
            std::cout << "Check Local Transaction,Received Message Topic:" << msg.getTopic() << ", MsgId:" << msg.getMsgId()
                      << std::endl;
            return COMMIT_MESSAGE;
        }
    };
    
    int main() {
        std::cout << "=======Before sending messages=======" << std::endl;
        //您在阿里云 RocketMQ 控制台上申请的 GID
        TransactionMQProducer producer("GID_XXXXXXXXXXXXXXXX");
        //设置 TCP 协议接入点,从阿里云 RocketMQ 控制台的实例详情页面获取
        producer.setNamesrvAddr("http://MQ_XXXXXXXXXXXX.mq-internet-access.mq-internet.aliyuncs.com:80");
        //您在阿里云账号管理控制台中创建的 AccessKeyId 和 AccessKeySecret 用于身份认证,用户渠道,默认值为:ALIYUN
        producer.setSessionCredentials("AK", "SK", "ALIYUN");
    
        //这只本地事务执行和回查函数
        ExampleTransactionListener *exampleTransactionListener = new ExampleTransactionListener();
        producer.setTransactionListener(exampleTransactionListener);
        //请确保参数设置完成之后启动 Producer
        producer.start();
        auto start = std::chrono::system_clock::now();
        int count = 3;
        for (int i = 0; i < count; ++i) {
            //发送消息时请设置您在阿里云 RocketMQ 控制台上申请的 Topic
            MQMessage msg("YOUR TRANSACTION TOPIC", "HiTAG", "Hello,CPP SDK, Transaction Message.");
            try {
                SendResult sendResult = producer.sendMessageInTransaction(msg, &i);
                std::cout << "SendResult:" << sendResult.getSendStatus() << ", Message ID: " << sendResult.getMsgId()
                          << std::endl;
                this_thread::sleep_for(chrono::seconds(1));
            } catch (MQException e) {
                std::cout << "ErrorCode: " << e.GetError() << " Exception:" << e.what() << std::endl;
            }
        }
        auto interval = std::chrono::system_clock::now() - start;
        std::cout << "Send " << count << " messages OK, costs "
                  << std::chrono::duration_cast<std::chrono::milliseconds>(interval).count() << "ms" << std::endl;
    
        std::cout << "Wait for local transaction check..... " << std::endl;
        for (int i = 0; i < 6; ++i) {
            this_thread::sleep_for(chrono::seconds(10));
            std::cout << "Running "<< i*10 + 10 << " Seconds......"<< std::endl;
        }
        producer.shutdown();
        std::cout << "=======After sending messages=======" << std::endl;
        return 0;
    }

消费事务消息

  1. 将以下代码拷贝到 ConsumerDemo.cpp 文件中,修改相应的参数后,使用 g++ 命令进行编译,生成可执行文件,即可直接运行。

    g++ -o consumer_demo -std=c++11 -lz -lrocketmq ConsumerDemo.cpp

  2. 消费事务消息的示例代码如下。
    #include <iostream>
    #include <thread>
    #include "DefaultMQPushConsumer.h"
    
    using namespace rocketmq;
    
    
    class ExampleMessageListener : public MessageListenerConcurrently {
    public:
        ConsumeStatus consumeMessage(const std::vector<MQMessageExt> &msgs) {
            for (auto item = msgs.begin(); item != msgs.end(); item++) {
                std::cout << "Received Message Topic:" << item->getTopic() << ", MsgId:" << item->getMsgId() << std::endl;
            }
            return CONSUME_SUCCESS;
        }
    };
    
    int main(int argc, char *argv[]) {
        std::cout << "=======Before consuming messages=======" << std::endl;
        //您在阿里云 RocketMQ 在控制台上申请的 GID
        DefaultMQPushConsumer *consumer = new DefaultMQPushConsumer("GID_XXXXXXXX");
        //设置 TCP 协议接入点,从阿里云 RocketMQ 控制台的实例详情页面获取
        consumer->setNamesrvAddr("http://MQ_INST_XXXXXXXXXXX.mq-internet-access.mq-internet.aliyuncs.com:80");
        //您在阿里云账号管理控制台中创建的 AccessKeyId 和 AccessKeySecret 用于身份认证,用户渠道,默认值为:ALIYUN
        consumer->setSessionCredentials("AK", "SK", "ALIYUN");
        auto start = std::chrono::system_clock::now();
    
    
    
        //register your own listener here to handle the messages received.
        //请注册自定义侦听函数用来处理接收到的消息,并返回响应的处理结果。
        ExampleMessageListener *messageListener = new ExampleMessageListener();
        consumer->subscribe("YOURTOPIC", "*");
        consumer->registerMessageListener(messageListener);
    
        //Start this consumer
        //准备工作完成,必须调用启动函数,才可以正常工作。
        // ********************************************
        // 1.确保订阅关系的设置在启动之前完成
        // 2.确保相同 GID 下面的消费者的订阅关系一致
        // *********************************************
        consumer->start();
    
        //Keep main thread running until process finished.
        //请保持线程常驻,不要执行 shutdown 操作
        std::this_thread::sleep_for(std::chrono::milliseconds(60 * 1000));
        consumer->shutdown();
        std::cout << "=======After consuming messages======" << std::endl;
        return 0;
    }