Brief introduction:

We all know that there are two major categories of popular distributed transactions: 2PC and TCC.

1.2 PC (Two-stage Submission)

If a writes data to database B, A tries to commit the data first, and B makes the state of the data unavailable

If a successfully tells B to confirm OK, B changes the data status to be available; otherwise, the data is deleted.

2.tcc(try confirm cancel)

Assume that A writes data to database B, B will try to lock the data. When A succeeds in calling the confirm method, and when A fails to cancel, B will implement the confirm and cancel methods.

Rocketmq uses the two-phase commit idea.

The message sender starts the transaction and sends the halfMessage. Upon receiving it, the broker puts it in a HF queue, saves it to disk, and sends a message acknowledgement to the message sender. The message sender receives the acknowledgement and commits after all the local logic has been executed so that the messages in the broker become available. If a COMMIT or rollback is not received within a short period of time, the broker will initiate a scheduled task to check the MESSAGE in the HF queue to see if the transaction is successful. If the message cannot be connected to the sender, the message will be removed after a certain period of time by default.

Example:

public class TransProducer { public static void main(String[] args) throws Exception{ TransactionMQProducer producer = new TransactionMQProducer("xxogp"); // Set the nameserver address producer.setNamesrvaddr ("localhost:9876"); Producer. SetTransactionListener (new TransactionListener () {/ / public LocalTransactionState execute transaction method executeLocalTransaction(Message message, Object o) { System.out.println("executeLocalTransaction====="); System.out.println(new String(message.getBody())); try { int i = 10*10; return LocalTransactionState.COMMIT_MESSAGE; } catch (Exception e) { return LocalTransactionState.ROLLBACK_MESSAGE; }} // check the method //Broker side callback, Public LocalTransactionState checkLocalTransaction(MessageExt MessageExt) { System.out.println("checkLocalTransaction====="); System.out.println(new String(messageExt.getBody())); String flagMessage = ""; If (" failed to perform the transaction ". The equals (flagMessage)) {/ / the message into a usable return LocalTransactionState. ROLLBACK_MESSAGE; } the if (" transaction execution success ". The equals (flagMessage)) {/ / delete directly hf message return LocalTransactionState.COM MIT_MESSAGE; } the if (" do not know whether success ". The equals (flagMessage)) {/ / don't know what situation will be to check the return LocalTransactionState. UNKNOW; } return LocalTransactionState.COMMIT_MESSAGE; }}); producer.start(); Message Message = new Message("mytop111", "hello".getbytes ()); TransactionSendResult send = producer.sendMessageInTransaction(message, null); System.out.println("send = " + send); }}Copy the code