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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM