在作者之前的 十二条后端开发经验分享,纯干货 文章中介绍的 优雅得Springboot + mybatis配置多数据源方式 里有很多小伙伴在评论区留言询问多个数据源同时在一个方法中使用时,事务是否会正常有效,这里作者 理论 + 实践 给大家解答一波,老规矩,附作者github地址:
- https://github.com/wayn111
一. 数据源跨库但是不跨 MySql 实例
这个形式就是数据源在同一个 MySQL 下,但是 jdbc-url 上的数据库配置不同,涉及多个数据库时,如果方法中发生异常,只有开启事务的数据源会发生回滚,其他数据源不会回滚。看到这里可能有点迷惑,什么是 只有开启事务的数据源会发生回滚,其他数据源不会回滚?
下面给出代码验证:
主数据源配置
@Slf4j
@EnableTransactionManagement
@EnableAspectJAutoProxy
@Configuration
@MapperScan(basePackages = "ltd.newbee.mall.core.dao", sqlSessionFactoryRef = "masterSqlSessionFactory")
public class Db1DataSourceConfig {
@Primary
@Bean
@ConfigurationProperties("spring.datasource.druid.master")
public DataSource masterDataSource(DruidProperties druidProperties) {
DruidDataSource build = DruidDataSourceBuilder.create().build();
return druidProperties.dataSource(build);
}
/**
* @param datasource 数据源
* @return SqlSessionFactory
* @Primary 默认SqlSessionFactory
*/
@Primary
@Bean(name = "masterSqlSessionFactory")
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource datasource,
Interceptor interceptor) throws Exception {
MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
bean.setDataSource(datasource);
// mybatis扫描xml所在位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath*:mapper/*.xml"));
bean.setTypeAliasesPackage("ltd.**.core.entity");
bean.setPlugins(interceptor);
GlobalConfig globalConfig = new GlobalConfig();
GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
dbConfig.setLogicDeleteField("isDeleted");
dbConfig.setLogicDeleteValue("1");
dbConfig.setLogicNotDeleteValue("0");
globalConfig.setDbConfig(dbConfig);
bean.setGlobalConfig(globalConfig);
log.info("masterDataSource 配置成功");
return bean.getObject();
}
@Primary
@Bean(name = "masterTransactionManager")
public DataSourceTransactionManager masterTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource)

本文探讨了Spring Boot项目中多数据源配置下事务的有效性问题,包括数据源在同一MySQL实例和不同MySQL实例的情况。介绍了使用Spring默认事务管理器时存在的问题,并给出了基于jta和seata两种解决方案。
最低0.47元/天 解锁文章
4691

被折叠的 条评论
为什么被折叠?



