数据源中没有datarow_想动态切换数据源咋办,别急,SpringBoot来帮你搞定

相信大家在随着公司的规模的不断发展,系统不断的增多,或多或少的可能会遇到多数据源的场景,不管是为了读写分离,还是需要聚合业务上的多数据,今天就给大家分享一下,SpringBoot多数据源的实现方案。首先先看一下实现步骤

实现步骤

  1. 使用一个枚举类来定义列出所有的数据源;
  2. 加载所有数据源到Spring容器中;
  3. 绑定数据源和枚举类定义的数据源的关系;
  4. 定义属性为ThreadLocal类来管理当前线程的数据源;
  5. 继承AbstractRoutingDataSource并重写determineCurrentLookupKey方法,在方法中用第4步方法来获取当前线程的数据源;
  6. 在使用的时候,需要在service或者dao层上,在调用Mapper先设置一下将要使用的数据源,不然走默认数据源(这步通常使用SpringAop方式来统一处理)

浅谈原理

主要是因为在调用mapper层getConnection时候,会先调用determineCurrentLookupKey方法来获取一个数据源(获取数据源的方法:先去AbstractRoutingDataSource中的targetDataSources中找,若没有找到则选择默认defaultTargetDataSource),然后在操作数据库。AbstractRoutingDataSource相关代码片段,主要在determineTargetDataSource时候调用我们重写determineCurrentLookupKey方法

public Connection getConnection() throws SQLException { return this.determineTargetDataSource().getConnection();}protected DataSource determineTargetDataSource() {  Object lookupKey = this.determineCurrentLookupKey(); DataSource dataSource = (DataSource)this.resolvedDataSources.get(lookupKey); }

工程目录结构

ef34b60f2b9a5dd140406277bc3178a9.png

实现代码

我这里的实现是使用业务线来模拟划分数据源的,大家可以里定义主从模式

1.使用一个枚举类来定义所有数据源;

public enum DataSourceKey { PRODUCT, USER,}

2.加载所有数据源到Spring容器中,这里使用@Primary注解来默认选择一个数据源注入,不然Spring会因为多数据来不知道选择哪个而报错。由于篇幅原因yml的文件放到另一篇文章中springBoot多数据源的yml配置,还请各位见谅。

@Configuration@EnableTransactionManagement@MapperScan(basePackages={"com.example.demo.mapper"})public class DataSourceConfiguration { @Value("${druid.type}") private Class extends DataSource> dataSourceType; @Bean(name = "userDataSource") @Primary @ConfigurationProperties(prefix = "druid.user") public DataSource masterDataSource(){ return DataSourceBuilder.create().type(dataSourceType).build(); } @Bean(name = "productDataSource") @ConfigurationProperties(prefix = "druid.product") public DataSource slaveDataSource1(){ return DataSourceBuilder.create().type(dataSourceType).build(); }}

3.绑定数据源和枚举类定义的数据源的关系;

@Configuration@AutoConfigureAfter({DataSourceConfiguration.class})public class DynamicConfig { static final String MAPPER_LOCATION = "classpath*:mapper/*/*Mapper.xml"; @Resource(name="userDataSource") private DataSource userDataSource; @Resource(name="productDataSource") private DataSource productDataSource; @Bean public RoutingDataSource dynamicDataSource(){ RoutingDataSource routingDataSource = new RoutingDataSource(); Map targetDataResources = new HashMap(); targetDataResources.put(DataSourceKey.USER, userDataSource); targetDataResources.put(DataSourceKey.PRODUCT,productDataSource); routingDataSource.setTargetDataSources(targetDataResources); routingDataSource.setDefaultTargetDataSource(userDataSource); return routingDataSource; } @Bean public DataSourceTransactionManager masterTransactionManager() { return new DataSourceTransactionManager(dynamicDataSource()); } @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dynamicDataSource()); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(DynamicConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); }}

4.定义属性为ThreadLocal类来管理当前线程的数据源;

public class DbContextHolder { private static final ThreadLocal contextHolder = new ThreadLocal(); public static void setDataSourceType(DataSourceKey dataSourceType) { contextHolder.remove(); contextHolder.set(dataSourceType); } public static DataSourceKey getDataSourceType() { return contextHolder.get(); } public static void clearDataSourceType() { contextHolder.remove(); }}

5.继承AbstractRoutingDataSource并重写determineCurrentLookupKey方法

public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DbContextHolder.getDataSourceType(); }}

6.使用SpringAop方式

@Aspect@Component@Order(20)public class DataSourceSelectorAspect { @Around(value="execution(* com.example.demo.mapper.product..*.*(..))") public Object useProductDataSource(ProceedingJoinPoint pjp) throws Throwable { try { DbContextHolder.setDataSourceType(DataSourceKey.PRODUCT); Object result = pjp.proceed(); DbContextHolder.clearDataSourceType(); return result; } finally { DbContextHolder.clearDataSourceType(); } } @Around(value="execution(* com.example.demo.mapper.user..*.*(..))") public Object useUserDataSource(ProceedingJoinPoint pjp) throws Throwable { try { DbContextHolder.setDataSourceType(DataSourceKey.USER); Object result = pjp.proceed(); DbContextHolder.clearDataSourceType(); return result; } finally { DbContextHolder.clearDataSourceType(); } }}

这样直接使用就可以根据不同模块下的mapper调用不同的数据源了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值