springboot2动态数据源的绑定

由于springboot2更新了绑定参数的api,部分springboot1用于绑定的工具类如RelaxedPropertyResolver已经无法在新版本中使用。本文实现参考了https://blog.csdn.net/catoop/article/details/50575038这篇文章,大致思路是一致的,如果需要详细实现可以参考。都是通过AbstractRoutingDataSource实现动态数据源的切换,以前我用spring配置多数据源的时候就是通过它实现的,有兴趣的可以了解下其原理,这里就不多赘述了。

 

废话不多说了,先上数据源注册工具类,springboot2与1的主要区别也就在这:

MultiDataSourceRegister.java:

package top.ivan.demo.springboot.mapper;

import com.zaxxer.hikari.HikariDataSource;
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 org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MultiDataSourceRegister implements EnvironmentAware, ImportBeanDefinitionRegistrar {

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

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

    private Environment evn; //配置上下文(也可以理解为配置文件的获取工具)

    private Map<String, DataSource> sourceMap;  //数据源列表

    private Binder binder; //参数绑定工具

    /**
     * ImportBeanDefinitionRegistrar接口的实现方法,通过该方法可以按照自己的方式注册bean
     *
     * @param annotationMetadata
     * @param beanDefinitionRegistry
     */
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        Map config, properties, defaultConfig = binder.bind("spring.datasource", Map.class).get(); //获取所有数据源配置
        sourceMap = new HashMap<>(); //默认配置
        properties = defaultConfig;
        String typeStr = evn.getProperty("spring.datasource.type"); //默认数据源类型
        Class<? extends DataSource> clazz = getDataSourceType(typeStr); //获取数据源类型
        DataSource consumerDatasource, defaultDatasource = bind(clazz, properties); //绑定默认数据源参数
        List<Map> configs = binder.bind("spring.datasource.multi", Bindable.listOf(Map.class)).get(); //获取其他数据源配置
        for (int i = 0; i < configs.size(); i++) { //遍历生成其他数据源
            config = configs.get(i);
            clazz = getDataSourceType((String) config.get("type"));
            if ((boolean) config.getOrDefault("extend", Boolean.TRUE)) { //获取extend字段,未定义或为true则为继承状态
                properties = new HashMap(defaultConfig); //继承默认数据源配置
                properties.putAll(config); //添加数据源参数
            } else {
                properties = config; //不继承默认配置
            }
            consumerDatasource = bind(clazz, properties); //绑定参数
            sourceMap.put(config.get("key").toString(), consumerDatasource); //获取数据源的key,以便通过该key可以定位到数据源
        }
        GenericBeanDefinition define = new GenericBeanDefinition(); //bean定义类
        define.setBeanClass(MultiDataSource.class); //设置bean的类型,此处MultiDataSource是继承AbstractRoutingDataSource的实现类
        MutablePropertyValues mpv = define.getPropertyValues(); //需要注入的参数,类似spring配置文件中的<property/>
        mpv.add("defaultTargetDataSource", defaultDatasource); //添加默认数据源,避免key不存在的情况没有数据源可用
        mpv.add("targetDataSources", sourceMap); //添加其他数据源
        beanDefinitionRegistry.registerBeanDefinition("datasource", define); //将该bean注册为datasource,不使用springboot自动生成的datasource
    }

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

    /**
     * 绑定参数,以下三个方法都是参考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) {
        this.evn = environment;
        binder = Binder.get(evn); //绑定配置器
    }
}

此处放出我的配置文件application.yml :

spring:
  datasource:
    password: 123456
    url: jdbc:mysql://127.0.0.1:3306/graduation_project?useUnicode=true&characterEncoding=UTF-8
    driver-class-name: com.mysql.jdbc.Driver
    username: ivan
    openMulti: true
    type: com.zaxxer.hikari.HikariDataSource
    idle-timeout: 30000
    multi:
    - key: default1
      password: 123456
      url: jdbc:mysql://127.0.0.1:3306/graduation_project?useUnicode=true&characterEncoding=UTF-8
      idle-timeout: 20000
      driver-class-name: com.mysql.jdbc.Driver
      username: ivan
      type: com.alibaba.druid.pool.DruidDataSource
    - key: gd
      password: 123456
      url: jdbc:mysql://gd.badtheway.xin:****/graduation_project?useUnicode=true&characterEncoding=UTF-8
      driver-class-name: com.mysql.jdbc.Driver
      username: ivan
mybatis:
  config-location: classpath:mapper/configure.xml
  mapper-locations: classpath:mapper/*Mapper.xml

这边说明一下,spring.datasource路径下的配置即默认数据源的配置,我是为了个人美感以及方便,所以在配置多数据源时使用spring.datasource.multi这个路径,假如需要更改的话修改MultiDataSourceRegister.java里面相应的值就可以了。

最后别忘了在@SpringBootApplication加上@Import(MultiDataSourceRegister.class)

 

下面是我自己使用的一些切面配置,通过@MultiDataSource$DataSource注解标记需要切换数据源的类,可以通过方法体参数->方法注解->类注解实现切换数据源。供大家参考:

MultiDataSource.java:

package top.ivan.demo.springboot.mapper;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.lang.annotation.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;
import java.util.Set;

public class MultiDataSource extends AbstractRoutingDataSource {

    private final static ThreadLocal<String> DATA_SOURCE_KEY = new ThreadLocal<>(); //保存当前线程的数据源对应的key

    private Set<Object> keySet;  //所有数据源的key集合

    private static void switchSource(String key) {
        DATA_SOURCE_KEY.set(key); //切换当先线程的key
    }

    private static void clear() {
        DATA_SOURCE_KEY.remove(); //移除key值
    }
    
    public static Object execute(String ds, Run run) throws Throwable {
        switchSource(ds);
        try {
            return run.run();
        } finally {
            clear();
        }
    }

    //AbstractRoutingDataSource抽象类实现方法,即获取当前线程数据源的key
    @Override
    protected Object determineCurrentLookupKey() {
        String key = DATA_SOURCE_KEY.get();
        if (!keySet.contains(key)) {
            logger.info(String.format("can not found datasource by key: '%s',this session may use default datasource", key));
        }
        return key;
    }

    /**
     * 在获取key的集合,目的只是为了添加一些告警日志
     */
    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
        try {
            Field sourceMapField = AbstractRoutingDataSource.class.getDeclaredField("resolvedDataSources");
            sourceMapField.setAccessible(true);
            Map<Object, javax.sql.DataSource> sourceMap = (Map<Object, javax.sql.DataSource>) sourceMapField.get(this);
            this.keySet = sourceMap.keySet();
            sourceMapField.setAccessible(false);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }
    
    public interface Run {
        Object run() throws Throwable;
    }

    /**
     * 用于获取AOP切点及数据源key的注解
     */
    @Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface DataSource {
        String value() default ""; //该值即key值
    }

    /**
     * 声明切面
     */
    @Component
    @Aspect
    @Order(-10)  //使该切面在事务之前执行
    public static class DataSourceSwitchInterceptor {

        /**
         * 扫描所有含有@MultiDataSource$DataSource注解的类
         */
        @Pointcut("@within(top.ivan.demo.springboot.mapper.MultiDataSource.DataSource)")
        public void switchDataSource() {
        }

        /**
         * 使用around方式监控
         * @param point
         * @return
         * @throws Throwable
         */
        @Around("switchDataSource()")
        public Object switchByMethod(ProceedingJoinPoint point) throws Throwable {
            Method method = getMethodByPoint(point); //获取执行方法
            Parameter[] params = method.getParameters(); //获取执行参数
            Parameter parameter;
            String source = null;
            boolean isDynamic = false;
            for (int i = params.length - 1; i >= 0; i--) { //扫描是否有参数带有@DataSource注解
                parameter = params[i];
                if (parameter.getAnnotation(DataSource.class) != null && point.getArgs()[i] instanceof String) {
                    source = (String) point.getArgs()[i]; //key值即该参数的值,要求该参数必须为String类型
                    isDynamic = true;
                    break;
                }
            }
            if (!isDynamic) { //不存在参数带有Datasource注解
                DataSource dataSource = method.getAnnotation(DataSource.class); //获取方法的@DataSource注解
                if (null == dataSource || !StringUtils.hasLength(dataSource.value())) { //方法不含有注解
                    dataSource = method.getDeclaringClass().getAnnotation(DataSource.class); //获取类级别的@DataSource注解
                }
                if (null != dataSource) {
                    source = dataSource.value(); //设置key值
                }
            }
            return persistBySource(source, point); //继续执行该方法
        }


        private Object persistBySource(String source, ProceedingJoinPoint point) throws Throwable {
            try {
                switchSource(source); //切换数据源
                return point.proceed(); //执行
            } finally {
                clear(); //清空key值
            }
        }

        private Method getMethodByPoint(ProceedingJoinPoint point) {
            MethodSignature methodSignature = (MethodSignature) point.getSignature();
            return methodSignature.getMethod();
        }
    }
    
}

示例:

package top.ivan.demo.springboot.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import top.ivan.demo.springboot.pojo.ProductPreview;

import java.util.List;

@Mapper
@MultiDataSource.DataSource("ds1")
public interface PreviewMapper {

    //使用ds的值作为key
    List<ProductPreview> getList(@Param("start") int start, @Param("count") int count, @MultiDataSource.DataSource String ds);

    //使用“ds2”作为key
    @MultiDataSource.DataSource("ds2")
    List<ProductPreview> getList2(@Param("start") int start, @Param("count") int count);
    
    //使用“ds1”作为key
    List<ProductPreview> getList3(@Param("start") int start, @Param("count") int count);

}

这几天刚接触springboot,还处于小白的状态,假如有什么问题的话欢迎大家指教

------------------------------------------------------------------------------------------------------------------------------

附上源码文件: https://files.cnblogs.com/files/badtheway/springboot.zip

posted @ 2018-05-19 17:39 Ivan_K 阅读(...) 评论(...) 编辑 收藏