SpringBoot多数据源动态切换数据源

1、配置多数据源

spring:
  datasource:
    master:
      password: erp_test@abc
      url: jdbc:mysql://127.0.0.1:3306/M201911010001?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
      driver-class-name: com.mysql.jdbc.Driver
      username: erp_test
      type: com.alibaba.druid.pool.DruidDataSource
      druid:
        initial-size: 5
        max-active: 150
        min-idle: 10
        max-wait: 6000
        web-stat-filter.enabled: true
        stat-view-servlet.enabled: true
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,wall,log4j
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
        useGlobalDataSourceStat: true
    cluster:
    - key: slave1
      password: erp_test@abc
      url: jdbc:mysql://127.0.0.1:3306/M201911010002?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
      idle-timeout: 20000
      driver-class-name: com.mysql.jdbc.Driver
      username: erp_test
      type: com.alibaba.druid.pool.DruidDataSource
      druid:
        initial-size: 5
        max-active: 150
        min-idle: 10
        max-wait: 6000
        web-stat-filter.enabled: true
        stat-view-servlet.enabled: true
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,wall,log4j
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
        useGlobalDataSourceStat: true
    - key: slave2
      password: erp_test@abc
      url: jdbc:mysql://127.0.0.1:3306/M201911010003?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
      idle-timeout: 20000
      driver-class-name: com.mysql.jdbc.Driver
      username: erp_test
      type: com.alibaba.druid.pool.DruidDataSource
      druid:
        initial-size: 5
        max-active: 150
        min-idle: 10
        max-wait: 6000
        web-stat-filter.enabled: true
        stat-view-servlet.enabled: true
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: SELECT 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxPoolPreparedStatementPerConnectionSize: 20
        filters: stat,wall,log4j
        connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
        useGlobalDataSourceStat: true
View Code

在上面我们配置了三个数据源,其中第一个作为默认数据源也就是我们的master数据源。主要是写操作,那么读操作交给我们的slave1跟slave2。
其中 master 数据源是一定要配置,作为我们的默认数据源;其次cluster集群中,其他的数据不配置也不会影响程序的运行(相当于单数据源),如果你想添加新的一个数据源 就在cluster下新增一个数据源即可,其中key为必须项,用于数据源的唯一标识,以及接下来切换数据源的标识。

2、注册数据源
在上面我们已经配置了三个数据源,但是这是我们自定义的配置,springboot是无法给我们自动配置,所以需要我们自己注册数据源.
那么就要实现 EnvironmentAware 用于读取上下文环境变量用于构建数据源,同时也需要实现 ImportBeanDefinitionRegistrar 接口注册我们构建的数据源。

package com.erp.db;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.boot.context.properties.source.ConfigurationPropertyNameAliases;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.MapConfigurationPropertySource;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;

import com.erp.config.DataSourceContext;
import com.zaxxer.hikari.HikariDataSource;

public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
    private static final Logger logger = LogManager.getLogger(DynamicDataSourceRegister.class);

    /**
     * 配置上下文(配置文件的获取工具)
     */
    private Environment evn;

    /**
     * 别名
     */
    private final static ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();

    /**
     * 由于部分数据源配置不同,所以在此处添加别名,避免切换数据源出现某些参数无法注入的情况
     */
    static {
        aliases.addAliases("url", new String[]{"jdbc-url"});
        aliases.addAliases("username", new String[]{"user"});
    }

    /**
     * 存储我们注册的数据源
     */
    private Map<String, DataSource> customDataSources = new HashMap<String, DataSource>();

    /**
     * 参数绑定工具 springboot2.0 新推出
     */
    private Binder binder;

    /**
     * ImportBeanDefinitionRegistrar接口的实现方法,通过该方法可以按照自己的方式注册bean
     *
     * @param annotationMetadata
     * @param beanDefinitionRegistry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        // 获取主数据源配置
        Map config, defauleDataSourceProperties;
        defauleDataSourceProperties = binder.bind("spring.datasource.master", Map.class).get();
        // 获取数据源类型
        String typeStr = evn.getProperty("spring.datasource.master.type");
        // 获取数据源类型
        Class<? extends DataSource> clazz = getDataSourceType(typeStr);
        // 绑定默认数据源参数 也就是主数据源
        DataSource consumerDatasource, defaultDatasource = bind(clazz, defauleDataSourceProperties);
        DataSourceContext.dataSourceIds.add("master");
        logger.info("注册默认数据源成功");
        
        // 获取其他数据源配置
        List<Map> configs = binder.bind("spring.datasource.cluster", Bindable.listOf(Map.class)).get();
        // 遍历从数据源
        for (int i = 0; i < configs.size(); i++) {
            config = configs.get(i);
            clazz = getDataSourceType((String) config.get("type"));
            defauleDataSourceProperties = config;
            // 绑定参数
            consumerDatasource = bind(clazz, defauleDataSourceProperties);
            // 获取数据源的key,以便通过该key可以定位到数据源
            String key = config.get("key").toString();
            customDataSources.put(key, consumerDatasource);
            // 数据源上下文,用于管理数据源与记录已经注册的数据源key
            DataSourceContext.dataSourceIds.add(key);
            logger.info("注册数据源{}成功", key);
        }
        // bean定义类
        GenericBeanDefinition define = new GenericBeanDefinition();
        // 设置bean的类型,此处DynamicRoutingDataSource是继承AbstractRoutingDataSource的实现类
        define.setBeanClass(MultiRouteDataSource.class);
        // 需要注入的参数
        MutablePropertyValues mpv = define.getPropertyValues();
        // 添加默认数据源,避免key不存在的情况没有数据源可用
        mpv.add("defaultTargetDataSource", defaultDatasource);
        // 添加其他数据源
        mpv.add("targetDataSources", customDataSources);
        // 将该bean注册为datasource,不使用springboot自动生成的datasource
        beanDefinitionRegistry.registerBeanDefinition("datasource", define);
        logger.info("注册数据源成功,一共注册{}个数据源", customDataSources.keySet().size() + 1);
    }

    /**
     * 通过字符串获取数据源class对象
     *
     * @param typeStr
     * @return
     */
    private Class<? extends DataSource> getDataSourceType(String typeStr) {
        Class<? extends DataSource> type;
        try {
            if (StringUtils.isNotBlank(typeStr)) {
                // 字符串不为空则通过反射获取class对象
                type = (Class<? extends DataSource>) Class.forName(typeStr);
            } else {
                // 默认为hikariCP数据源,与springboot默认数据源保持一致
                type = HikariDataSource.class;
            }
            
            return type;
        } catch (Exception e) {
            //无法通过反射获取class对象的情况则抛出异常,该情况一般是写错了,所以此次抛出一个runtimeexception
            throw new IllegalArgumentException("can not resolve class with type: " + typeStr); 
        }
    }

    /**
     * 绑定参数,以下三个方法都是参考DataSourceBuilder的bind方法实现的,目的是尽量保证我们自己添加的数据源构造过程与springboot保持一致
     *
     * @param result
     * @param properties
     */
    private void bind(DataSource result, Map properties) {
        ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
        Binder binder = new Binder(new ConfigurationPropertySource[]{source.withAliases(aliases)});
        // 将参数绑定到对象
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
    }

    private <T extends DataSource> T bind(Class<T> clazz, Map properties) {
        ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
        Binder binder = new Binder(new ConfigurationPropertySource[]{source.withAliases(aliases)});
        // 通过类型绑定参数并获得实例对象
        return binder.bind(ConfigurationPropertyName.EMPTY, Bindable.of(clazz)).get();
    }

    /**
     * @param clazz
     * @param sourcePath 参数路径,对应配置文件中的值,如: spring.datasource
     * @param <T>
     * @return
     */
    private <T extends DataSource> T bind(Class<T> clazz, String sourcePath) {
        Map properties = binder.bind(sourcePath, Map.class).get();
        return bind(clazz, properties);
    }

    /**
     * EnvironmentAware接口的实现方法,通过aware的方式注入,此处是environment对象
     *
     * @param environment
     */
    @Override
    public void setEnvironment(Environment environment) {
        logger.info("开始注册数据源");
        this.evn = environment;
        // 绑定配置器
        binder = Binder.get(evn);
    }
}

上面代码需要注意的是在springboot2.x系列中用于绑定的工具类如RelaxedPropertyResolver已经无法使用,现在使用Binder代替。上面代码主要是读取application中数据源的配置,先读取spring.datasource.master构建默认数据源,然后在构建cluster中的数据源。

在这里注册完数据源之后,我们需要通过@import注解把我们的数据源注册器导入到spring中
在启动类WebApplication.java加上如下注解@Import(DynamicDataSourceRegister.class)。
其中我们用到了一个 DataSourceContext 中的静态变量来保存我们已经注册成功的数据源的key,至此我们的数据源注册就已经完成了。

/**
 * 启动类
 **/
@EnableScheduling
@EnableRetry
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
//注册动态多数据源
@Import(DynamicDataSourceRegister.class)
public class WebApplication {

    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(WebApplication.class);
        springApplication.addListeners(new ApplicationReadyEventListener());
        springApplication.run(args);
    }

}

 



3、配置数据源上下文
我们需要新建一个数据源上下文,用户记录当前线程使用的数据源的key是什么,以及记录所有注册成功的数据源的key的集合。对于线程级别的私有变量,我们首先ThreadLocal来实现。

package com.erp.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 数据源上下文
 * 
 * 数据源上下文的作用:用户记录当前线程使用的数据源的key是什么,以及记录所有注册成功的数据源的key的集合。
 *
 * @author Lynch
 */
public class DataSourceContext {
    private static final Logger log = LogManager.getLogger(DataSourceContext.class);
    
    //线程级别的私有变量
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
    
    //存储已经注册的数据源的key
    public static List<String> dataSourceIds = new ArrayList<>();

    public static void setRouterKey(String routerKey) {
        log.debug("切换至{}数据源", routerKey);
        contextHolder.set(routerKey);
    }

    public static String getRouterKey() {
        return contextHolder.get();
    }

    /**
     * 设置数据源之前一定要先移除
     * 
     * @author Lynch
     */
    public static void clearRouterKey() {
        contextHolder.remove();
    }

    /**
     * 判断指定DataSrouce当前是否存在
     *
     * @param dataSourceId
     */
    public static boolean containsDataSource(String dataSourceId){
        return dataSourceIds.contains(dataSourceId);
    }

}

 

4、动态数据源路由
前面我们以及新建了数据源上下文,用于存储我们当前线程的数据源key那么怎么通知spring用key当前的数据源呢,查阅资料可知,spring提供一个接口,名为AbstractRoutingDataSource的抽象类,我们只需要重写determineCurrentLookupKey方法就可以,这个方法看名字就知道,就是返回当前线程的数据源的key,那我们只需要从我们刚刚的数据源上下文中取出我们的key即可,那么具体代码取下。

package com.erp.db;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.erp.config.DataSourceContext;

/**
 * DataSource路由类
 * 
 * 重写的函数决定了最后选择的DataSource
 *
 * @author Lynch
 */
public class MultiRouteDataSource extends AbstractRoutingDataSource {
    
    @Override
    protected Object determineCurrentLookupKey() {
        // 通过绑定线程的数据源上下文实现多数据源的动态切换
        return DataSourceContext.getRouterKey();
    }
}

5、切换自己想要使用的数据源

public UserVO findUser(String username) {
    DataSourceContext.setDataSource("slave");
    UserVO userVO = userMapper.findByVO(username);
    System.out.println(userVO.getName());
    return null;
}

这种是在业务中使用代码设置数据源的方式,也可以使用AOP+注解的方式实现控制,还可以前端头部设置后端通过拦截器统一设置!

 

6、拦截器统一设置——ApiAuthInterceptor

String alias = request.getHeader("alias");
if(StringUtils.isEmpty(alias)) {
    alias = "default";
}

//拦截器设置数据源
DataSourceContext.setRouterKey(alias);
1、数据库
IP/PORT:182.*.*.60:33064
用户名/密码:erp_more/erp_more#abc123
数据库名:M201911010001、M201911010002、M201911010003

2、接口地址:
http://182.61.131.62:33061/

3、多数据源调用方法
http头部传alias参数,表示访问不同的数据库,目前alias值包含master、M201911010002、M201911010003

4、动态新增数据源
如果想添加新的一个数据源,就在cluster下新增一个数据源即可,其中key为必须项,用于数据源的唯一标识,以及切换数据源的标识。

配置文件在/xinya_web/src/main/resources/application-more.yml

 

 

本文参考自此文

posted on 2019-11-05 15:31  Ruthless  阅读(5328)  评论(0编辑  收藏  举报