多数据源事务
boolean logXaCommand = true;
Connection localConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8","root","123456");
XAConnection xaLocal = new MysqlXAConnection((com.mysql.cj.jdbc.JdbcConnection)localConn,logXaCommand);
XAResource localResource = xaLocal.getXAResource();
Connection onlineConn = DriverManager.getConnection("jdbc:mysql://ip:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8","username","password");
XAConnection xaOnline = new MysqlXAConnection((JdbcConnection)onlineConn,logXaCommand);
XAResource onlineResource = xaOnline.getXAResource();
byte[] globalTransactionId = "global_123456".getBytes();
int formatId = 1;
try{
byte[] branchTransactionId = "branch_123456".getBytes();
Xid xid1 = new MysqlXid(globalTransactionId,branchTransactionId,formatId);
localResource.start(xid1,XAResource.TMNOFLAGS);
PreparedStatement statement = localConn.prepareStatement("insert into market(market_name) values('"+System.currentTimeMillis()+"')");
statement.execute();
localResource.end(xid1,XAResource.TMSUCCESS);
byte[] branchTransactionIdTwo = "branch_888888".getBytes();
Xid xid2 = new MysqlXid(globalTransactionId,branchTransactionIdTwo,formatId);
onlineResource.start(xid2,XAResource.TMNOFLAGS);
PreparedStatement preparedStatement = onlineConn.prepareStatement("insert into student(username) values('admin_username')");
preparedStatement.execute();
onlineResource.end(xid2,XAResource.TMSUCCESS);
int localPrepare = localResource.prepare(xid1);
int onlinePrepare = onlineResource.prepare(xid2);
boolean oneParse = false;
if(localPrepare == XAResource.XA_OK && onlinePrepare == XAResource.XA_OK){
localResource.commit(xid1,oneParse);
onlineResource.commit(xid2,oneParse);
}else{
localResource.rollback(xid1);
onlineResource.rollback(xid2);
}
}catch (XAException e){
e.printStackTrace();
}