XA实现多数据源事务

多数据源事务

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();
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值