基于springboot的单应用多数据源的事务管理简单实现
作者:互联网
SpringBoot单应用多数据源的分布式事务管理方案:
-
XA实现方案;
在java中通过Spring+JTA的方式实现
在pom文件中引入jar包:
<!--jta+atomikos分布式事务--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jta-atomikos</artifactId> </dependency>
编写一个配置数据源的java类:
@Configuration @MapperScan(basePackages = {"配置该数据源配置对应的数据源(mapper的路径)"}, sqlSessionFactoryRef = "userdbSqlSessionFactory") public class UserDBDataSource4jtaConfig { @Value("${spring.datasource.userdb.username}") private String username; @Value("${spring.datasource.userdb.password}") private String password; @Value("${spring.datasource.userdb.driverClassName}") private String driverClassName; @Value("${spring.datasource.userdb.jdbcUrl}") private String jdbcUrl; /** * 配置一个数据源的bean * @return */ @Bean(name = "userdbDataSource") public DataSource userdbDataSource() { //创建一个XA数据源 MysqlXADataSource xaDataSource = new MysqlXADataSource(); xaDataSource.setUrl(jdbcUrl); xaDataSource.setUser(username); xaDataSource.setPassword(password); AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean(); atomikosDataSourceBean.setXaDataSource(xaDataSource); atomikosDataSourceBean.setUniqueResourceName("userdbDataSource"); atomikosDataSourceBean.setMaxPoolSize(30); atomikosDataSourceBean.setMinPoolSize(5); return atomikosDataSourceBean; } @Bean(name = "userdbSqlSessionFactory") public SqlSessionFactory userdbSqlSessionFactory(@Qualifier("userdbDataSource") DataSource userdbDataSource) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(userdbDataSource); return sqlSessionFactoryBean.getObject(); } @Bean(name = "userdbSqlSessionTemplate") public SqlSessionTemplate userdbSqlSessionTemplate(@Qualifier("userdbSqlSessionFactory") SqlSessionFactory userdbSqlSessionFactory) { return new SqlSessionTemplate(userdbSqlSessionFactory); } }
使用:然后在具体的serviceimpl方法中添加
@Transactional
注解即可。
标签:事务管理,springboot,atomikosDataSourceBean,userdbDataSource,数据源,spring,userdbSqlSess 来源: https://www.cnblogs.com/zhaojunjin/p/14964851.html