两个数据库假设在不同的服务器,不同的实例.
-
drop database db1;
-
drop database db2;
-
create database db1;
-
use db1;
-
create table t(translog int primary key,ts timestamp default current_timestamp);
-
-
create database db2;
-
use db2;
-
create table t(translog int primary key,ts timestamp default current_timestamp);
-
insert into t(translog) values(10);
db2的t表,增加一个tid为10的数据
一般应用程序,先写一个库提交,然后再写一个库.
假如第二个库事务失败,则事务补偿第一个库.
避免分布式事务是架构设计的重点.
可以采用如下的方式,减小不一致发生的概率.
-
import java.sql.Connection;
-
import java.sql.DriverManager;
-
import java.sql.PreparedStatement;
-
import java.sql.SQLException;
-
-
public class Test {
-
-
private synchronized static Connection getConnection(String dbName) {
-
String URL = "jdbc:mysql://127.0.0.1:3306/" + dbName;
-
String USERNAME = "xx";
-
String PWD = "xx";
-
Connection con = null;
-
try {
-
Class.forName("com.mysql.jdbc.Driver");
-
con = DriverManager.getConnection(URL, USERNAME, PWD);
-
con.setAutoCommit(false);
-
} catch (SQLException e) {
-
} catch (ClassNotFoundException e) {
-
}
-
return con;
-
}
-
-
public void insertDB(Connection con, int translogid) throws SQLException {
-
-
PreparedStatement pt;
-
pt = con.prepareStatement("insert into t(translog) values(?)");
-
pt.setInt(1, translogid);
-
pt.execute();
-
-
}
-
-
public void insertTranslogid(int translogid) {
-
Connection db1 = getConnection("db1");
-
Connection db2 = getConnection("db2");
-
try {
-
insertDB(db1, translogid);
-
insertDB(db2, translogid);
-
} catch (SQLException e) {
-
e.printStackTrace();
-
try {
-
db1.rollback();
-
db2.rollback();
-
db1.close();
-
db2.close();
-
return;
-
} catch (SQLException ex) {
-
ex.printStackTrace();
-
return;
-
}
-
}
-
-
try {
-
db1.commit();
-
db2.commit();
-
db1.close();
-
db2.close();
-
} catch (SQLException e) {
-
e.printStackTrace();
-
}
-
}
-
-
public static void main(String[] args) throws ClassNotFoundException, SQLException {
-
Test t = new Test();
-
for (int i = 0; i <= 10; i++) {
-
t.insertTranslogid(i);
-
}
-
}
-
}
先执行写db1,但是并不提交.接着写db2.
如果写两个库,都没有发生异常.则一起提交.否则一起回滚.
执行上述程序,在translogid为10的时候,db2有主键冲突的异常.db1会回滚已经写入的数据.
这个模式有一个缺点.
db1的锁持有时间和连接持有时间,增加了一倍.因为他要等待db2的处理结果.
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-2119080/
,如需转载,请注明出处,否则将追究法律责任。