springboot添加多数据源 以及 动态添加数据源动态切换数据源

<!-- Druid 数据连接池依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
//指定使用Druid做数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

//数据源配置一
spring.datasource.sod.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.sod.validationQuery=SELECT 1 FROM DUAL
spring.datasource.sod.filters=stat,wall
spring.datasource.sod.url=jdbc:oracle:thin:@192.168.**.***:1521:xxxx
spring.datasource.sod.username=xxx
spring.datasource.sod.password=xxx //数据源配置二
spring.datasource.base.url=jdbc:oracle:thin:@192.168.**.**:1521:xxxx
spring.datasource.base.username=xxx
spring.datasource.base.password=xxx

多数据源配置:

在熟悉了单实例数据源的实现后,不难看出,在Spring Boot中,通过为该数据源DataSource初始化一个与之对应的SessionFactory,从而实现连接。因此在面对多数据源的时候,可以分别为每个数据源写一个mybatis的config类,使其每个DataSource都拥有一个只属于自己的SessionFactory,这样就可以根据各自的mapper映射目录找到对应的mybaits实例; 
这种实现方法要求不同的mybatis实例的mapper映射目录不能相同

把一个配置类作下的Bean命名统一,并注入相应的Bean,从而可以保证每一个SessionFactory所对应的配置信息唯一;具体配置如下: 
第一个数据源的配置

SodDataSourceConfig

package com.ch.XX.fetch.config.ds;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource;
import java.util.Properties; @Configuration
//扫描 Mapper 接口并容器管理
@MapperScan(basePackages = SodDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "sodSqlSessionFactory")
public class SodDataSourceConfig { // 精确到 sod 目录,以便跟其他数据源隔离
static final String PACKAGE = "com.ch.oneservice.fetch.sodDao";//DAO所在目录
static final String MAPPER_LOCATION = "classpath:mapper/sod/*Mapper.xml";//Mapper.xml所在目录 @Value("${spring.datasource.type}")
private Class<? extends DataSource> dataSourceType;//数据源类型 @Bean(name = "sodDataSource")
@ConfigurationProperties(prefix = "spring.datasource.sod") //application.property中配置文件的前缀
public DataSource sodDataSource() {
return DataSourceBuilder.create().type(dataSourceType).build();
} @Bean(name = "sodPageHelper")
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("dialect", "oracle");
pageHelper.setProperties(p);
return pageHelper;
} @Bean(name = "sodTransactionManager")
public DataSourceTransactionManager baseTransactionManager() {
return new DataSourceTransactionManager(sodDataSource());
} @Bean(name = "sodSqlSessionFactory")
public SqlSessionFactory baseSqlSessionFactory(@Qualifier("sodDataSource") DataSource sodDataSource,
@Qualifier("sodPageHelper") PageHelper sodPageHelper)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(sodDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(SodDataSourceConfig.MAPPER_LOCATION));
sessionFactory.setPlugins(new Interceptor[]{sodPageHelper});
return sessionFactory.getObject();
}
}

第二个数据源类似

BaseDataSourceConfig

package com.ch.oneservice.fetch.config.ds;

import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource;
import java.util.Properties; @Configuration
// 扫描 Mapper 接口并容器管理
@MapperScan(basePackages = BaseDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "baseSqlSessionFactory")
public class BaseDataSourceConfig { // 精确到 master 目录,以便跟其他数据源隔离
static final String PACKAGE = "com.ch.oneservice.fetch.dao";
static final String MAPPER_LOCATION = "classpath:mapper/base/*Mapper.xml"; @Value("${spring.datasource.type}")
private Class<? extends DataSource> dataSourceType; @Bean(name = "baseDataSource")
@ConfigurationProperties(prefix = "spring.datasource.base")
@Primary
public DataSource baseDataSource() {
return DataSourceBuilder.create().type(dataSourceType).build();
} @Bean(name = "basePageHelper")
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("dialect", "oracle");
pageHelper.setProperties(p);
return pageHelper;
} @Bean(name = "baseTransactionManager")
@Primary
public DataSourceTransactionManager baseTransactionManager() {
return new DataSourceTransactionManager(baseDataSource());
} @Bean(name = "baseSqlSessionFactory")
@Primary
public SqlSessionFactory baseSqlSessionFactory(@Qualifier("baseDataSource") DataSource baseDataSource,
@Qualifier("basePageHelper") PageHelper basePageHelper)
throws Exception {
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(baseDataSource);
sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources(BaseDataSourceConfig.MAPPER_LOCATION));
sessionFactory.setPlugins(new Interceptor[]{basePageHelper});
return sessionFactory.getObject();
}
}

完成配置文件的配置后,可在工程目录的mapper包下新建两个目录:UserMapper和StudentMapper,分别对应两个数据源。这两个目录只能同级,或者不同目录,不能互为子父目录。

然后使用的时候只需要把相应数据库资源的业务层代码写到对应的包下,项目就可以自己匹配相应的SqlSessionFactory去执行相应的查询

动态数据源加载:

参考如下文章:https://blog.csdn.net/YHYR_YCY/article/details/78894940  写的很详细,我就不重复造*了

 
上一篇:Javascript 进阶 继承


下一篇:Effective c++(笔记) 之 杂项讨论