1.分布式事务
说到分布式事务,可以理解为,由于分布式而引起的事务不一致的问题。随着项目做大,模块拆分,数据库拆分。一次包含增删改操作数据库涉及到了更新两个不同物理节点的数据库,这样的数据库事务只能保证自己处理的部分的事务,但是整个的事务就不能保证一致性。
针对分布式事务常见的例子有:生成订单
例如订单表和订单明细表不在一个数据库中,生成订单的时候要确保对应的订单明细信息应该也要同步插入进去,
如果不用分布式事务,会出现订单插入成功,订单明细数据库宕机了,订单明细插入失败的情况。
2.JTA
JTA(java Transaction API)是JavaEE 13 个开发规范之一。java 事务API,允许应用程序执行分布式事务处理——在两个或多个网络计算机资源上访问并且更新数据。JDBC驱动程序的JTA支持极大地增强了数据访问能力。事务最简单最直接的目的就是保证数据的有效性,数据的一致性。
3.atomikos
atomikos 是一个为Java平台提供增值服务的并且开源类事务管理器。
org.springframework.boot
spring-boot-starter-jta-atomikos
spring:
application: jta-atomikos
datasource:
db1:
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/orders?useSSL=false&serverTimezone=GMT%2b8&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
username: root
password: 123456
db2:
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/orderdetails?useSSL=false&serverTimezone=GMT%2b8&characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
username: root
password: 123456
server:
port: 8004
db1数据源配置读取类
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.db1")
@Data
public class DB1Config {
private String username;
private String password;
private String jdbcUrl;
}
db2数据源配置读取类
@Configuration
@ConfigurationProperties(prefix = "spring.datasource.db2")
@Data
public class DB2Config {
private String username;
private String password;
private String jdbcUrl;
}
db1的数据源配置
@Configuration
@MapperScan(basePackages = {"com.ljm.boot.jtaatomikos.mapper.db1"}, sqlSessionFactoryRef = "sqlSessionFactoryDb1")
public class DbSessionFactory1 {
@Bean(name = "db1")
public DataSource businessDbDataSource(@Qualifier("DB1Config") Db1Config db1Conf) {
MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
mysqlXaDataSource.setUrl(db1Conf.getJdbcUrl());
mysqlXaDataSource.setPassword(db1Conf.getPassword());
mysqlXaDataSource.setUser(db1Conf.getUsername());
mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
xaDataSource.setXaDataSource(mysqlXaDataSource);
xaDataSource.setUniqueResourceName("db1");
return xaDataSource;
}
@Bean(name="sqlSessionFactoryDb1")
public SqlSessionFactory sqlSessionFactoryDb1(@Qualifier("db1")DataSource DataSource) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(DataSource);
return factoryBean.getObject();
}
@Bean(name="sqlSessionTemplateDb1")
public SqlSessionTemplate sqlSessionTemplateDb1(@Qualifier("sqlSessionFactoryDb1") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
db2数据源配置
@MapperScan(basePackages = {"com.ljm.boot.jtaatomikos.mapper.db2"}, sqlSessionFactoryRef = "sqlSessionFactoryDb2")
public class DbSessionFactory2 {
@Bean(name = "db2")
public DataSource newhomeDbDataSource(@Qualifier("DB2Config") DB2Config db2Conf) {
MysqlXADataSource mysqlXaDataSource = new MysqlXADataSource();
mysqlXaDataSource.setUrl(db2Conf.getJdbcUrl());
mysqlXaDataSource.setPassword(db2Conf.getPassword());
mysqlXaDataSource.setUser(db2Conf.getUsername());
mysqlXaDataSource.setPinGlobalTxToPhysicalConnection(true);
AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
xaDataSource.setXaDataSource(mysqlXaDataSource);
xaDataSource.setUniqueResourceName("db2");
return xaDataSource;
}
@Bean(name="sqlSessionFactoryDb2")
public SqlSessionFactory sqlSessionFactoryDb2(@Qualifier("db2")DataSource DataSource ) throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(DataSource);
return factoryBean.getObject();
}
@Bean(name="sqlSessionTemplateDb2")
public SqlSessionTemplate sqlSessionTemplateDb2(@Qualifier("sqlSessionFactoryDb2") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
db1数据持久化操作
@Mapper
public interface OrderMapper {
@Insert("INSERT INTO orders(id, name) VALUES(#{id}, #{name})")
int insert(@Param("id") String id, @Param("name") String name);
}
db2数据持久化操作
@Mapper
public interface OrderDetailMapper {
@Insert("INSERT INTO orderdetails(id, orderId) VALUES(#{id}, #{orderId})")
int insert(@Param("id") int id, @Param("orderId") String orderId);
}
create database orders;
use orders;
create table orders(
id varchar(40),
name varchar(25)
);
create database orderdetails;
use orderdetails;
create table orderdetails(
id int,
ordcerId varchar(40)
);
@Service
public class OrderServiceImpl implements OrderService {
@Resource
private OrderMapper orderMapper;
@Resource
private OrderDetailMapper orderDetailMapper;
@Override
@Transactional
public String insertDbaAndDbB(boolean flag) {
//实际生产环境订单id应该通关雪花算法生成(生产的id是数字类型,b+树索引查询效率会很高),uuid没有规律,会严重影响索引查找速度
String orderId = UUID.randomUUID().toString();
//插入订单
orderMapper.insert(orderId, "重入门到放弃");
//模拟报错,事务会回滚
if(flag){
//flag=true的时候,触发异常,事务回滚,为false的话,两个数据库都能正确插入数据
System.out.println(1 / 0);
}
//插入订单明细
orderDetailMapper.insert(1, orderId);
return "success";
}
}
github地址
要是觉得我写的对你有点帮助的话,麻烦在github上帮我点 Star
【SpringBoot框架篇】其它文章如下,后续会继续更新。