Spring Boot 多库分布式事务,最简配置,没有之一

Java基础

浏览数:95

2020-5-30


Spring Boot 多库分布式事务,最简配置

上一篇文章中,我就对spring boot 整合mysql,Druid,atomikos,出了一个方案,但是相对还是代码比较多,但是这个对版本冲突,不兼容的影响较小,下面说说我认为最简单的配置:

1、加入核心包pom.xml

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>${mybatis-spring-boot-starter.version}</version>
</dependency>
<!-- 阿里 连接池 -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>${druid.version}</version>
</dependency>
<!--分布式事务支持 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>

2、application.yml

spring:
  jta:
    enabled: true
    service: com.atomikos.icatch.standalone.UserTransactionServiceFactory
    max-actives: 200
    enable-logging: false
    atomikos: 
      datasource:
        oneData:
          unique-resource-name: dataSourceOne
          xa-data-source-class-name: com.alibaba.druid.pool.xa.DruidXADataSource
          xa-properties:
            driverClassName: com.mysql.jdbc.Driver
            username: root
            url: jdbc:mysql://192.168.1.206:3306/testTwo?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
            password: "1234"
        twoData:
          unique-resource-name: dataSourceTwo
          xa-data-source-class-name: com.alibaba.druid.pool.xa.DruidXADataSource
          xa-properties:
            driverClassName: com.mysql.jdbc.Driver
            username: root
            url: jdbc:mysql://192.168.1.206:3306/testTwo?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false
            password: "1234"
logging:
  level:
    com.xin.dream.one.dao: debug
    com.xin.dream.two.dao: debug
    

3、配置DataSource一

@Configuration
@MapperScan(basePackages = "com.xin.dream.one.dao", sqlSessionFactoryRef="oneSqlSessionFactory")
public class OneDatabaseConfig {
	
	@Primary
	@Bean(name = "oneDataSource", destroyMethod = "close")
	@ConfigurationProperties(prefix = "spring.jta.atomikos.datasource.oneData")
	public DataSource oneDataSource() {
		return new AtomikosDataSourceBean();
	}

	@Primary
	@Bean(name = "oneSqlSessionFactory")
	public SqlSessionFactory oneSqlSessionFactory(@Qualifier("oneDataSource") DataSource oneDataSource)throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(oneDataSource);
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setMapperLocations(resolver.getResources("classpath:com/xin/dream/one/mapper/*.xml"));
		return bean.getObject();
	}
}

敲黑板了哦:DataSource其它数据源同上,不过不能要@Primary注解,数据库的配置根据自己的需求添加。
坑来了:如果你的数据库密码是纯数字,要加引号如:“1234”,不然会报错=数据类型不匹配。
PS:这个配置也木有加sqlsessiontemplate哈,不过还是建议加。

 

 

微信群在QQ群中发,QQ技术群

作者:KINBUG-BP