すべてのプロダクト
Search
ドキュメントセンター

ApsaraMQ for RocketMQ:トランザクションメッセージの送受信

最終更新日:Jul 09, 2024

ApsaraMQ for RocketMQは、拡張アーキテクチャ (X/Open XA) と同様の分散トランザクション処理機能を提供し、ApsaraMQ for RocketMQのトランザクションの一貫性を確保します。 このトピックでは、HTTPクライアントSDK for Javaを使用してトランザクションメッセージを送受信する方法に関するサンプルコードを提供します。

背景情報

次の図は、トランザクションメッセージの対話プロセスを示しています。

图片1.png

詳細については、「トランザクションメッセージ」をご参照ください。

の前提条件

開始する前に、次の操作が実行されていることを確認してください。

  • SDK for Javaをインストールします。 詳細については、「環境の準備」をご参照ください。

  • ApsaraMQ for RocketMQコンソールのコードで指定するリソースを作成します。 リソースには、インスタンス、トピック、および消費者グループが含まれます。 詳細については、「リソースの作成」 をご参照ください。

  • Alibaba CloudアカウントのAccessKeyペアを取得します。 詳細については、「AccessKey の作成」をご参照ください。

トランザクションメッセージの送信

次のサンプルコードは、Java用HTTPクライアントSDKを使用してトランザクションメッセージを送信する方法の例を示しています。

import com.aliyun.mq.http.MQClient;
import com.aliyun.mq.http.MQTransProducer;
import com.aliyun.mq.http.common.AckMessageException;
import com.aliyun.mq.http.model.Message;
import com.aliyun.mq.http.model.TopicMessage;

import java.util.List;

public class TransProducer {


    static void processCommitRollError(Throwable e) {
        if (e instanceof AckMessageException) {
            AckMessageException errors = (AckMessageException) e;
            System.out.println("Commit/Roll transaction error, requestId is:" + errors.getRequestId() + ", fail handles:");
            if (errors.getErrorMessages() != null) {
                for (String errorHandle :errors.getErrorMessages().keySet()) {
                    System.out.println("Handle:" + errorHandle + ", ErrorCode:" + errors.getErrorMessages().get(errorHandle).getErrorCode()
                            + ", ErrorMsg:" + errors.getErrorMessages().get(errorHandle).getErrorMessage());
                }
            }
        }
    }

    public static void main(String[] args) throws Throwable {
        MQClient mqClient = new MQClient(
                // The HTTP endpoint. You can obtain the endpoint in the HTTP Endpoint section of the Instance Details page in the ApsaraMQ for RocketMQ console. 
                "${HTTP_ENDPOINT}",
                // Make sure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are configured. 
                // The AccessKey ID that is used for authentication. 
	              System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
	              // The AccessKey secret that is used for authentication. 
	              System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        );

        // The topic in which the message is produced. You must create the topic in the ApsaraMQ for RocketMQ console. 
        // Each topic can be used to send and receive messages of a specific type. For example, a topic that is used to send and consume normal messages cannot be used to send or receive messages of other types. 
        final String topic = "${TOPIC}";
        // The ID of the instance to which the topic belongs. You must create the instance in the ApsaraMQ for RocketMQ console. 
        // If the instance has a namespace, specify the ID of the instance. If the instance does not have a namespace, set the instanceID parameter to null or an empty string. You can obtain the namespace of the instance on the Instance Details page in the ApsaraMQ for RocketMQ console. 
        final String instanceId = "${INSTANCE_ID}";
        // The ID of the consumer group that you created in the ApsaraMQ for RocketMQ console. 
        final String groupId = "${GROUP_ID}";

        final MQTransProducer mqTransProducer = mqClient.getTransProducer(instanceId, topic, groupId);

        for (int i = 0; i < 4; i++) {
            TopicMessage topicMessage = new TopicMessage();
            topicMessage.setMessageBody("trans_msg");
            topicMessage.setMessageTag("a");
            topicMessage.setMessageKey(String.valueOf(System.currentTimeMillis()));
            // The time interval between the sending time of the transactional message and the start time of the first check for the status of the local transaction. This time interval specifies the relative time when the status is first checked. Unit: seconds. Valid values: 10 to 300. 
            // If the message is not committed or rolled back after the first transaction status check is performed, the broker initiates a request to check the status of the local transaction at an interval of 10 seconds within the next 24 hours. 
            topicMessage.setTransCheckImmunityTime(10);
            topicMessage.getProperties().put("a", String.valueOf(i));

            TopicMessage pubResultMsg = null;
            pubResultMsg = mqTransProducer.publishMessage(topicMessage);
            System.out.println("Send---->msgId is: " + pubResultMsg.getMessageId()
                    + ", bodyMD5 is: " + pubResultMsg.getMessageBodyMD5()
                    + ", Handle: " + pubResultMsg.getReceiptHandle()
            );
            if (pubResultMsg != null && pubResultMsg.getReceiptHandle() != null) {
                if (i == 0) {
                    // After the producer sends the transactional message, the broker obtains the handle of the half message that corresponds to the transactional message and commits or rolls back the transactional message based on the status of the handle. 
                    try {
                        mqTransProducer.commit(pubResultMsg.getReceiptHandle());
                        System.out.println(String.format("MessageId:%s, commit", pubResultMsg.getMessageId()));
                    } catch (Throwable e) {
                        // If the transactional message is not committed or rolled back before the period of time specified by the TransCheckImmunityTime parameter for the handle of the transactional message elapses, the commit or rollback operation fails. 
                        if (e instanceof AckMessageException) {
                            processCommitRollError(e);
                            continue;
                        }
                    }
                }
            }
        }

        // The client needs a thread or a process to process unacknowledged transactional messages. 
        // Start a thread to process unacknowledged transactional messages. 
        Thread t = new Thread(new Runnable() {
            public void run() {
                int count = 0;
                while(true) {
                    try {
                        if (count == 3) {
                            break;
                        }
                        List<Message> messages = mqTransProducer.consumeHalfMessage(3, 3);
                        if (messages == null) {
                            System.out.println("No Half message!");
                            continue;
                        }
                        System.out.println(String.format("Half---->MessageId:%s,Properties:%s,Body:%s,Latency:%d",
                                messages.get(0).getMessageId(),
                                messages.get(0).getProperties(),
                                messages.get(0).getMessageBodyString(),
                                System.currentTimeMillis() - messages.get(0).getPublishTime()));

                        for (Message message : messages) {
                            try {
                                if (Integer.valueOf(message.getProperties().get("a")) == 1) {
                                    // Confirm to commit the transactional message. 
                                    mqTransProducer.commit(message.getReceiptHandle());
                                    count++;
                                    System.out.println(String.format("MessageId:%s, commit", message.getMessageId()));
                                } else if (Integer.valueOf(message.getProperties().get("a")) == 2
                                        && message.getConsumedTimes() > 1) {
                                    // Confirm to commit the transactional message. 
                                    mqTransProducer.commit(message.getReceiptHandle());
                                    count++;
                                    System.out.println(String.format("MessageId:%s, commit", message.getMessageId()));
                                } else if (Integer.valueOf(message.getProperties().get("a")) == 3) {
                                    // Confirm to roll back the transactional message. 
                                    mqTransProducer.rollback(message.getReceiptHandle());
                                    count++;
                                    System.out.println(String.format("MessageId:%s, rollback", message.getMessageId()));
                                } else {
                                    // Check the status next time. 
                                    System.out.println(String.format("MessageId:%s, unknown", message.getMessageId()));
                                }
                            } catch (Throwable e) {
                                // If the transactional message is committed or rolled back after the time specified by the TransCheckImmunityTime parameter for the handle of the transactional message elapses or after the timeout period specified for the handle of consumeHalfMessage elapses, the commit or rollback fails. In this example, the timeout period is specified as 10 seconds for the handle of consumeHalfMessage. 
                                processCommitRollError(e);
                            }
                        }
                    } catch (Throwable e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
        });

        t.start();

        t.join();

        mqClient.close();
    }

}

トランザクションメッセージの購読

次のサンプルコードは、Java用HTTPクライアントSDKを使用してトランザクションメッセージをサブスクライブする方法の例を示しています。

import com.aliyun.mq.http.MQClient;
import com.aliyun.mq.http.MQConsumer;
import com.aliyun.mq.http.common.AckMessageException;
import com.aliyun.mq.http.model.Message;

import java.util.ArrayList;
import java.util.List;

public class Consumer {

    public static void main(String[] args) {
        MQClient mqClient = new MQClient(
                // The HTTP endpoint. You can obtain the endpoint in the HTTP Endpoint section of the Instance Details page in the ApsaraMQ for RocketMQ console. 
                "${HTTP_ENDPOINT}",
                // Make sure that the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are configured. 
                // The AccessKey ID that is used for authentication. 
	              System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
	              // The AccessKey secret that is used for authentication. 
	              System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
        );

        // The topic in which the message is produced. You must create the topic in the ApsaraMQ for RocketMQ console. 
        // Each topic can be used to send and receive messages of a specific type. For example, a topic that is used to send and receive normal messages cannot be used to send or receive messages of other types. 
        final String topic = "${TOPIC}";
        // The ID of the consumer group that you created in the ApsaraMQ for RocketMQ console. 
        final String groupId = "${GROUP_ID}";
        // The ID of the instance to which the topic belongs. You must create the instance in the ApsaraMQ for RocketMQ console. 
        // If the instance has a namespace, specify the ID of the instance. If the instance does not have a namespace, set the instanceID parameter to null or an empty string. You can obtain the namespace of the instance on the Instance Details page in the ApsaraMQ for RocketMQ console. 
        final String instanceId = "${INSTANCE_ID}";

        final MQConsumer consumer;
        if (instanceId != null && instanceId != "") {
            consumer = mqClient.getConsumer(instanceId, topic, groupId, null);
        } else {
            consumer = mqClient.getConsumer(topic, groupId);
        }

        // Cyclically consume messages in the current thread. We recommend that you use multiple threads to concurrently consume messages. 
        do {
            List<Message> messages = null;

            try {
                // Consume messages in long polling mode. 
                // In long polling mode, if no message in the topic is available for consumption, the request is suspended on the broker for the specified period of time. If a message becomes available for consumption within the specified period of time, the broker immediately sends a response to the consumer. In this example, the value is specified as 3 seconds. 
                messages = consumer.consumeMessage(
                        3,// Specify the maximum number of messages that can be consumed at a time. In this example, the value is specified as 3. The maximum value that you can specify is 16. 
                        3// The duration of a long polling cycle. Unit: seconds. In this example, the value is specified as 3. The maximum value you can specify is 30. 
                );
            } catch (Throwable e) {
                e.printStackTrace();
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            // No message in the topic is available for consumption. 
            if (messages == null || messages.isEmpty()) {
                System.out.println(Thread.currentThread().getName() + ": no new message, continue!");
                continue;
            }

            // The message consumption logic. 
            for (Message message : messages) {
                System.out.println("Receive message: " + message);
            }

            // If the broker does not receive an acknowledgment (ACK) for a message from the consumer before the delivery retry interval elapses, the broker sends the message for consumption again. 
            // A unique timestamp is specified for the handle of a message each time the message is consumed. 
            {
                List<String> handles = new ArrayList<String>();
                for (Message message : messages) {
                    handles.add(message.getReceiptHandle());
                }

                try {
                    consumer.ackMessage(handles);
                } catch (Throwable e) {
                    // If the handle of a message times out, the broker cannot receive an ACK for the message from the consumer. 
                    if (e instanceof AckMessageException) {
                        AckMessageException errors = (AckMessageException) e;
                        System.out.println("Ack message fail, requestId is:" + errors.getRequestId() + ", fail handles:");
                        if (errors.getErrorMessages() != null) {
                            for (String errorHandle :errors.getErrorMessages().keySet()) {
                                System.out.println("Handle:" + errorHandle + ", ErrorCode:" + errors.getErrorMessages().get(errorHandle).getErrorCode()
                                        + ", ErrorMsg:" + errors.getErrorMessages().get(errorHandle).getErrorMessage());
                            }
                        }
                        continue;
                    }
                    e.printStackTrace();
                }
            }
        } while (true);
    }
}