spring boot 2.x 使用druid+ mybatis 配置多数据源

POM 依赖

使用的spring boot 2.1.9 RELEASE ;druid的版本是 1.1.20 ;mybatis的版本是 2.1.0

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

		<!-- druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.20</version>
		</dependency>

		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.0</version>
		</dependency>

application.yaml配置

参考druid官方说明:

Spring Boot 2.X 版本不再支持配置继承,多数据源的话每个数据源的所有配置都需要单独配置,否则配置不会生效

所以在多个数据源的配置需要单独配置。这里需要注意的是多个数据源的配置区分是要在druid后面。开始参考其他的 "one" 写在datasource 之后: datasource-one ,但是实际下面的参数都么有起作用。

spring:
  datasource:
  	   # 数据源one
      druid-one:
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: root
          password: yskj2018%%%
          url: jdbc:mysql://192.168.3.188:3306/fqpay?useUnicode=true&characterEncoding=utf-8
          type: com.alibaba.druid.pool.DruidDataSource
          initial-size: 10
          max-active: 100
          min-idle: 10
          max-wait: 10000
          time-between-eviction-runs-millis: 60000
          min-evictable-idle-time-millis: 30000
          validation-query: select 'x'
          # 申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
          test-on-borrow: false
          # 归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
          test-on-return: false
          #申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
          test-while-idle: true
          pool-prepared-statements: true
          max-open-prepared-statements: 20
          filter:
            stat:
              enabled: true
              log-slow-sql: true
              slow-sql-millis: 10000
              db-type: mysql
      # 数据源two        
      druid-two:
          driver-class-name: com.mysql.cj.jdbc.Driver
          username: root
          password: yskj2018%%%
          url: jdbc:mysql://192.168.3.188:3306/xffq?useUnicode=true&characterEncoding=utf-8
          type: com.alibaba.druid.pool.DruidDataSource
          initial-size: 10
          max-active: 100
          min-idle: 10
          max-wait: 10000
          time-between-eviction-runs-millis: 60000
          min-evictable-idle-time-millis: 30000
          validation-query: select 'x'
          # 申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
          test-on-borrow: false
          # 归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
          test-on-return: false
          #申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
          test-while-idle: true
          pool-prepared-statements: true
          max-open-prepared-statements: 20
          filter:
            stat:
              enabled: true
              log-slow-sql: true
              slow-sql-millis: 10000
              db-type: mysql

DataSource的配置

@Configuration
public class DataSourceConfig {
	
	//指定名称
	@Bean(name = "oneDataSource")
	@Qualifier("oneDataSource")
	//指定配置的前缀
	@ConfigurationProperties(prefix = "spring.datasource.druid-one")
	public DataSource  dataSourceOne(){
		//这里使用DruidDataSourceBuilder
		return DruidDataSourceBuilder.create().build();
	}
	
	
	
	@Bean(name="twoDataSource")
	@Qualifier("twoDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.druid-two")
	public DataSource dataSourceTwo() {
		return DruidDataSourceBuilder.create().build();
	}
	
	//分别配置事物管理
	@Bean(name = "oneTransaction")
	public DataSourceTransactionManager db1TransactionManager(
		@Qualifier("oneDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}
	
	@Bean(name = "twoTransaction")
	public DataSourceTransactionManager db2TransactionManager(
		@Qualifier("twoDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

}

Mybatis 配置

同样,在配置文件中进行区分

# mybatis
mybatis-one:
  type-aliases-package: com.demo.model.one
  #mapper映射文件 
  #mapper-locations: "classpath*:mapper/one/*.xml"
  #mybaits配置文件
  #config-location:
  configuration:
    # 数据库下划线自动转化成驼峰规则
    map-underscore-to-camel-case: true
    # 打印SQL语句
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

mybatis-two:
  type-aliases-package: com.demo.model.two
  #mapper映射文件
  #mapper-locations: "classpath*:mapper/two/*.xml"
  #mybaits配置文件
  #config-location:
  configuration:
    # 数据库下划线自动转化成驼峰规则
    map-underscore-to-camel-case: true
    # 打印SQL语句
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

分别来配置 mybatis

one数据源的:

@Configuration
@MapperScan ( basePackages = {"com.demo.model.one" },
	sqlSessionFactoryRef = "oneSqlSessionFactoryBean" )
@Slf4j
public class MyBatisOneConfig {
	
	@Resource ( name = "oneDataSource" )
	private DataSource dataSource;
	
	private static final String MAPPER_XML = "classpath:mapper/one/*.xml";
	
	@Bean ( name = "oneSqlSessionFactoryBean" )
	@ConfigurationProperties ( prefix = "mybatis-one" )
	public SqlSessionFactory oneSqlSessionFactoryBean () throws Exception {
		
		try {
			SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean ();
			sessionFactory.setDataSource (dataSource);
			sessionFactory.setMapperLocations (
				new PathMatchingResourcePatternResolver ()
					.getResources (MAPPER_XML));
			return sessionFactory.getObject ();
		} catch ( Exception e ) {
			log.error ("Could not confiure mybatis session factory" + e.getMessage (), e);
			return null;
		}
	}
	
}

two数据源:

@Configuration
@MapperScan(basePackages = {"com.demo.model.two"},
		sqlSessionFactoryRef = "twoSqlSessionFactoryBean")
@Slf4j
public class MyBatisTwoConfig {
	
	@Resource( name = "twoDataSource")
	private DataSource  dataSourceTwo;
	
	private static final  String XFFQ_XML = "classpath:mapper/two/*.xml";
	
	@Bean(name = "twoSqlSessionFactoryBean")
	@ConfigurationProperties (prefix = "mybatis-two")
	public SqlSessionFactory twoSqlSessionFactoryBean() throws Exception {
		try {
			SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
			sessionFactoryBean.setDataSource (dataSourceTwo);
			sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(XFFQ_XML));
			return  sessionFactoryBean.getObject ();
		} catch (Exception e) {
			log.error("Could not confiure mybatis session factory"+e.getMessage(),e);
			return null;
		}
	}
	
}

这里说明一下,两个数据源的mapper是分开的,XML配置文件也是分开的,@MapperScan是分别扫描。
事物,在service的是类中,可以在需要增加事物的方法体上加上事物注解,
如下:

	@Transactional (value ="twoTransaction", rollbackFor = Exception.class)
	@Override
	public void saveEntity ( TestEntity entity ) {
		mapper.insertEntity (entity);		
		if (1<2){
			throw new RuntimeException("事物测试");
		}
	}

上述为个人学习记录,如有错误,请指出。

最后待解决的是 多数据源的数据一致性问题。

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页