测试SpringBoot2使用JTA组件实现基于mybatis-plus多数据源事务管理(亲测好用)
测试SpringBoot2使用JTA组件实现基于mybatis-plus多数据源事务管理(亲测好用)
继上一篇实现基于JdbcTemplate的多数据源事务管理成功后,接着想到了那么Atomikos事务管理是否对mybatis-plus多数据源也同样适用呢?带着这个疑问我做了一个简单的实验,过程如下
准备工作(这里跟上篇文章用的环境都一样)
这里我们将使用最基础的JdbcTemplate来实现数据访问,所以如果你还不会使用JdbcTemplate配置多数据源,建议先看一下JdbcTemplate的多数据源配置。
场景设定:
假设我们有两个库,分别为:test1和test2
这两个库中都有一张User表,我们希望这两张表中的数据是一致的
假设这两张表中都已经有一条数据:name=aaa,age=30;因为这两张表中数据是一致的,所以要update的时候,就必须两个库中的User表更新时候,要么都成功,要么都失败。
1、核心依赖
<!--JTA组件核心依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>
2、环境配置
yml配置文件这里jtaManager的配置,在日志输出中非常关键。
spring:
jta:
enabled: true
transaction-manager-id: jtaManager
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.jdbc.Driver
backdatasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/test2?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.jdbc.Driver
3、jta组件配置类
package com.sgcc.qfjs.config;
import com.mysql.jdbc.jdbc2.optional.MysqlXADataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class JtaDataSourceConfig {
@Autowired
private Environment env;
@Autowired
private DataSourceProperties properties;
@Bean
@Primary
public DataSource primaryDatasource() {
//数据库链接
MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
mysqlXADataSource.setUrl(properties.getUrl());
mysqlXADataSource.setUser(properties.getUsername());
mysqlXADataSource.setPassword(properties.getPassword());
mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);
//事务管理
AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
atomikosDataSourceBean.setXaDataSource(mysqlXADataSource);
atomikosDataSourceBean.setUniqueResourceName("dataSource");
return atomikosDataSourceBean;
}
@Bean
public DataSource backDatasource() {
//数据库链接
MysqlXADataSource mysqlXADataSource = new MysqlXADataSource();
mysqlXADataSource.setUrl(env.getProperty("spring.backdatasource.url"));
mysqlXADataSource.setUser(env.getProperty("spring.backdatasource.username"));
mysqlXADataSource.setPassword(env.getProperty("spring.backdatasource.password"));
mysqlXADataSource.setPinGlobalTxToPhysicalConnection(true);
//事务管理
AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
atomikosDataSourceBean.setXaDataSource(mysqlXADataSource);
atomikosDataSourceBean.setUniqueResourceName("backDataSource");
return atomikosDataSourceBean;
}
@Bean("primaryTemplate")
public JdbcTemplate primaryTemplate(){
return new JdbcTemplate(primaryDatasource());
}
@Bean("backTemplate")
public JdbcTemplate batchTemplate(){
return new JdbcTemplate(backDatasource());
}
}
4、mybatis配置文件,由于是双数据源,这里配置了两个
主数据库配置文件MybatisPlusConfigOne
package com.sgcc.qfjs.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.sgcc.qfjs.module.mapper"},sqlSessionTemplateRef = "primarySessionTemplate")
public class MybatisPlusConfigOne {
@Autowired
private DataSource primaryDatasource;
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor page = new PaginationInterceptor();
page.setLimit(-1);
page.setDialectType("mysql");
return page;
}
@Primary
@Bean(name = "sqlSessionFactoryOne")
public SqlSessionFactory sqlSessionFactoryOne() throws Exception {
MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
mybatisPlus.setDataSource(primaryDatasource);
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
mybatisPlus.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return mybatisPlus.getObject();
}
@Primary
@Bean(name = "primarySessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(
@Qualifier("sqlSessionFactoryOne") SqlSessionFactory sqlSessionFactoryOne) {
// 配置Session模板
return new SqlSessionTemplate(sqlSessionFactoryOne);
}
}
数据库配置文件MybatisPlusConfigTwo
package com.sgcc.qfjs.config;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.sgcc.qfjs.module.mappertwo"},sqlSessionTemplateRef = "backSessionTemplate")
public class MybatisPlusConfigTwo {
/**
* 这里有坑,@Autowired 注解是按照类型装配的不能把backDatasource,注入进来
*/
@Resource
private DataSource backDatasource;
/**
* 分页插件
*/
@Bean(name = "paginationInterceptortwo")
public PaginationInterceptor paginationInterceptortwo() {
PaginationInterceptor page = new PaginationInterceptor();
page.setLimit(-1);
page.setDialectType("mysql");
return page;
}
@Bean(name = "sqlSessionFactoryTwo")
public SqlSessionFactory sqlSessionFactoryTwo() throws Exception {
MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
mybatisPlus.setDataSource(backDatasource);
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
mybatisPlus.setMapperLocations(resolver.getResources("classpath:mappertwo/*.xml"));
return mybatisPlus.getObject();
}
@Bean(name = "backSessionTemplate")
public SqlSessionTemplate sqlSessionTemplate(
@Qualifier("sqlSessionFactoryTwo") SqlSessionFactory sqlSessionFactoryTwo) {
// 配置Session模板
return new SqlSessionTemplate(sqlSessionFactoryTwo);
}
}
注意一个注入的坑
/**
* 这里有坑,@Autowired 注解是按照类型装配的不能把backDatasource注入进来,这里要用名称装配@Resource
*/
@Resource
private DataSource backDatasource;
5、测试服务类CatTestServiceImpl
package com.sgcc.qfjs.module.service.impl;
/**
* <p>
* 服务实现类
* </p>
*
* @author wkf
* @since 2020-09-16
*/
@Service
@Slf4j
public class CatTestServiceImpl extends ServiceImpl<CatTestMapper, CatTest> implements CatTestService {
@Autowired
private CatTesttwoService catTesttwoService;
@Override
@Transactional
public void tx() {
// 修改test1库中的数据
this.baseMapper.tx();
// 修改test2库中的数据
catTesttwoService.tx();
}
@Override
@Transactional
public void tx2() {
// 修改test1库中的数据
this.baseMapper.tx();
// 模拟:修改test2库之前抛出异常
throw new RuntimeException();
}
}
这里tx函数,是两句update操作,一般都会成功;而tx2函数中,我们人为的制造了一个异常,这个异常是在test1库中的数据更新后才产生的,这样就可以测试一下test1更新成功,之后是否还能在JTA的帮助下实现回滚。
6、创建测试类,编写测试用例
@RunWith(SpringRunner.class)
@SpringBootTest
public class AppTest {
@Autowired
private CatTestService catTestService;
@Test
public void test1() throws Exception {
// 正确更新的情况
catTestService.tx();
}
@Test
public void test2() throws Exception {
// 更新失败的情况
try {
catTestService.tx2();
} catch (Exception e) {
e.printStackTrace();
}
}
}
这里有两个测试用例:
test1:因为没有故意制造的异常,不出意外两个库的update都会成功,所以根据name=aaa去把两个数据查出来,看age是否都被更新到了40。
test2:tx2函数会把test1中name=aaa的用户age更新为50,然后抛出异常,JTA事务生效的话,会把age回滚回40,所以这里的检查也是两个库的aaa用户的age应该都为50,这样就意味着JTA事务生效,保证了test1和test2两个库中的User表数据更新一致,没有制造出脏数据。
7、测试验证
执行test1成功,查看数据库数据是否更新成功
执行test2成功,查看数据库数据是否回滚成功
2022-07-28 11:09:04.999|DEBUG|main|com.atomikos.logging.Slf4jLogger|Line:32| XAResource.rollback ( 6A74614D616E61676572313635383937373734343831353030303031:6A74614D616E6167657231 ) on resource dataSource represented by XAResource instance com.mysql.jdbc.jdbc2.optional.JDBC4SuspendableXAConnection@339b45f8
2022-07-28 11:09:05.010|DEBUG|main|com.atomikos.logging.Slf4jLogger|Line:32| rollback() done of transaction jtaManager165897774481500001
2022-07-28 11:09:05.010|DEBUG|main|com.atomikos.logging.Slf4jLogger|Line:32| rollback() done of transaction jtaManager165897774481500001