jta mysql_JTA 使用 MySQL 分布式事务

public classJTA_MySQL {public static voidmain(String[] args) {

XADataSource xaDs1=JTA_MySQL.getDataSource("jdbc:mysql://172.30.60.126:3306/db_zhang", "root","root");

XAConnection xaCon1= null;

XAResource xaRes1= null;

Connection conn1= null;

Statement stmt1= null;

XADataSource xaDs2=JTA_MySQL.getDataSource("jdbc:mysql://172.30.60.124:3306/db_zhang", "root","root");

XAConnection xaCon2= null;

XAResource xaRes2= null;

Connection conn2= null;

Statement stmt2= null;int ret1 = 0;int ret2 = 0;

Xid xid1= new MyXid(100, new byte[] { 0x01 }, new byte[] { 0x02 });

Xid xid2= new MyXid(100, new byte[] { 0x01 }, new byte[] { 0x03 });try{

xaCon1=getXAConnetion(xaDs1);

conn1=getConnection(xaCon1);

stmt1=conn1.createStatement();

xaRes1=xaCon1.getXAResource();

xaCon2=getXAConnetion(xaDs2);

conn2=getConnection(xaCon2);

stmt2=conn2.createStatement();

xaRes2=xaCon2.getXAResource();

xaRes1.start(xid1, XAResource.TMNOFLAGS);

stmt1.execute("delete from person where id=1");

xaRes1.end(xid1, XAResource.TMSUCCESS);

xaRes2.start(xid2, XAResource.TMNOFLAGS);

stmt2.execute("insert into person select 1, 'zhang'");

xaRes2.end(xid2, XAResource.TMSUCCESS);

ret1=xaRes1.prepare(xid1);

ret2=xaRes2.prepare(xid2);if (XAResource.XA_OK == ret1 && XAResource.XA_OK ==ret2) {

xaRes1.commit(xid1,false);

xaRes2.commit(xid2,false);

System.out.println("提交分布式事务");

}else{

xaRes1.rollback(xid1);

xaRes2.rollback(xid2);

System.out.println("回退分布式事务");

}

}catch(SQLException e) {

e.printStackTrace();

}catch(XAException e) {

e.printStackTrace();

}

}private staticXADataSource getDataSource(String url, String user,

String password) {

MysqlXADataSource dataSource= newMysqlXADataSource();

dataSource.setUrl(url);

dataSource.setUser(user);

dataSource.setPassword(password);returndataSource;

}public staticXAConnection getXAConnetion(XADataSource dataSource) {

XAConnection XAConn= null;try{

XAConn=dataSource.getXAConnection();

}catch(SQLException e) {

e.printStackTrace();

}returnXAConn;

}public staticConnection getConnection(XAConnection XAConn) {

Connection conn= null;try{

conn=XAConn.getConnection();

}catch(SQLException e) {

e.printStackTrace();

}returnconn;

}public static voidcloseConnection(Connection conn) {try{

conn.close();

}catch(SQLException e) {

System.out.println("连接关闭失败");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值