@Override
public TransactionSendResult sendMessageInTransaction(final Message msg,
final Object arg) throws MQClientException {
if (null == this.transactionListener) {
throw new MQClientException(“TransactionListener is null”, null);
}
return this.defaultMQProducerImpl.sendMessageInTransaction(msg, null, arg);
}
…
}
在DefaultMQProducerImpl
中进行事务消息调用,关键步骤在代码中进行了标注,如下所示:
public class DefaultMQProducerImpl implements MQProducerInner {
…
public TransactionSendResult sendMessageInTransaction(final Message msg,
final LocalTransactionExecuter localTransactionExecuter, final Object arg)
throws MQClientException {
TransactionListener transactionListener = getCheckListener();
if (null == localTransactionExecuter && null == transactionListener) {
throw new MQClientException(“tranExecutor is null”, null);
}
//1、进行消息检测
Validators.checkMessage(msg, this.defaultMQProducer);
SendResult sendResult = null;
//2、设置事务消息
MessageAccessor.putProperty(msg, MessageConst.PROPERTY_TRANSACTION_PREPARED, “true”);
MessageAccessor.putProperty(msg, MessageConst.PROPERTY_PRODUCER_GROUP, this.defaultMQProducer.getProducerGroup());
try {
//3、同步发送事务消息
sendResult = this.send(msg);
} catch (Exception e) {
throw new MQClientException(“send message Exception”, e);
}
LocalTransactionState localTransactionState = LocalTransactionState.UNKNOW;
Throwable localException = null;
switch (sendResult.getSendStatus()) {
case SEND_OK: {
try {
if (sendResult.getTransactionId() != null) {
msg.putUserProperty(“transactionId”, sendResult.getTransactionId());
}
String transactionId = msg.getProperty(MessageConst.PROPERTY_UNIQ_CLIENT_MESSAGE_ID_KEYIDX);
//4、发送成功,设置transactionId
if (null != transactionId && !“”.equals(transactionId)) {
msg.setTransactionId(transactionId);
}
if (null != localTransactionExecuter) {
localTransactionState = localTransactionExecuter.executeLocalTransactionBranch(msg, arg);
} else if (transactionListener != null) {
log.debug(“Used new transaction API”);
//5、执行本地事务,获取本地事务执行状态
localTransactionState = transactionListener.executeLocalTransaction(msg, arg);
}
if (null == localTransactionState) {
localTransactionState = LocalTransactionState.UNKNOW;
}
if (localTransactionState != LocalTransactionState.COMMIT_MESSAGE) {
log.info(“executeLocalTransactionBranch return {}”, localTransactionState);
log.info(msg.toString());
}
} catch (Throwable e) {
log.info(“executeLocalTransactionBranch exception”, e);
log.info(msg.toString());
localException = e;
}
}
break;
case FLUSH_DISK_TIMEOUT:
case FLUSH_SLAVE_TIMEOUT:
case SLAVE_NOT_AVAILABLE:
localTransactionState = LocalTransactionState.ROLLBACK_MESSAGE;
break;
default:
break;
}
try {
//6、更具本地事务执行状态,执行半消息的提交或者回滚