SpringBoot動態數據源切換(一)

最近項目中需要配置兩個數據源,并且在不同的包下動態切換,為此,參考網上動態切換數據源的博客,實現了滿足項目的數據源動態切換功能。


  • 1、Spring的開發者還是挺有先見之明的,為我們提供了擴展Spring的AbstractRoutingDataSource抽象類,我們來看它的源碼
    /**
     * Retrieve the current target DataSource. Determines the
     * {@link #determineCurrentLookupKey() current lookup key}, performs
     * a lookup in the {@link #setTargetDataSources targetDataSources} map,
     * falls back to the specified
     * {@link #setDefaultTargetDataSource default target DataSource} if necessary.
     * @see #determineCurrentLookupKey()
     */
    protected DataSource determineTargetDataSource() {
        Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
        Object lookupKey = determineCurrentLookupKey();
        DataSource dataSource = this.resolvedDataSources.get(lookupKey);
        if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
            dataSource = this.resolvedDefaultDataSource;
        }
        if (dataSource == null) {
            throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
        }
        return dataSource;
    }

    /**
     * Determine the current lookup key. This will typically be
     * implemented to check a thread-bound transaction context.
     * <p>Allows for arbitrary keys. The returned key needs
     * to match the stored lookup key type, as resolved by the
     * {@link #resolveSpecifiedLookupKey} method.
     */
    protected abstract Object determineCurrentLookupKey();

源碼注釋解釋的很清楚,determineTargetDataSource 方法通過數據源的標識獲取當前數據源;determineCurrentLookupKey方法則是獲取數據源標識。(作為英語彩筆,有道詞典這種翻譯軟件還是特別好使的)

所以,我們實現動態切換數據源,需要實現determineCurrentLookupKey方法,動態提供數據源標識即可。

  • 2、自定義DynamicDataSource類,繼承AbstractRoutingDataSource,并實現determineCurrentLookupKey方法。
    public class DynamicDataSource extends AbstractRoutingDataSource {
    
        @Override
        protected Object determineCurrentLookupKey() {
            /**
             * DynamicDataSourceContextHolder代碼中使用setDataSource
             * 設置當前的數據源,在路由類中使用getDataSource進行獲取,
             * 交給AbstractRoutingDataSource進行注入使用。
             */
            return DynamicDataSourceContextHolder.getDataSource();
        }
    }
  • 3、創建統一數據源管理類DynamicDataSourceContextHolder
    public class DynamicDataSourceContextHolder {
    
        // 線程本地環境
        private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();
        // 管理所有的數據源Id
        public static List<String> dataSourceIds = new ArrayList<String>();
        
        public static void setDataSource(String dataSource) {
            dataSources.set(dataSource);
        }
        public static String getDataSource() {
            return dataSources.get();
        }
        public static void clearDataSource() {
            dataSources.remove();
        }
        
        // 判斷指定的DataSource當前是否存在
        public static boolean containsDataSource(String dataSourceId) {
            return dataSourceIds.contains(dataSourceId);
        }
    }
  • 4、重點來了,創建動態數據源注冊器DynamicDataSourceRegister
    public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    // 默認數據連接池
    public static final Object DATASOURCE_TYPE_DEFAULT = "org.apache.tomcat.jdbc.pool.DataSource";

    private Class<? extends DataSource> dataSourceType;

    // 默認數據源
    private DataSource defaultDataSource;

    private Map<String, DataSource> dataSourceMaps = new HashMap<String, DataSource>();

    /**
     * 加載多數據源配置
     * @param environment
     */
    @Override
    public void setEnvironment(Environment environment) {
        initDefaultDataSource(environment);
    }

    /**
     * 初始化默認數據源
     * @param environment
     */
    private void initDefaultDataSource(Environment environment) {
        RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource.");
        try {
            if(propertyResolver.getProperty("type") == null) {
                dataSourceType = (Class<? extends DataSource>)Class.forName(DATASOURCE_TYPE_DEFAULT.toString());
            } else {
                dataSourceType = (Class<? extends DataSource>)Class.forName(propertyResolver.getProperty("type"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        // 創建數據源
        String jndiName = propertyResolver.getProperty("jndi-name");
        String[] jndiNames = jndiName.split(",");
        defaultDataSource = new JndiDataSourceLookup().getDataSource(jndiNames[0]);

        dataSourceMaps.put("AAA", defaultDataSource);
        DataSource dataSource1 = new JndiDataSourceLookup().getDataSource(jndiNames[1]);
        dataSourceMaps.put("BBB", dataSource1);
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        Map<String, Object> targetDataSources = new HashMap<String, Object>();
        // 將主數據源添加到更多數據源中
        targetDataSources.put("dataSource", defaultDataSource);
        DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");

        // 添加更多數據源
        targetDataSources.putAll(dataSourceMaps);
        for(String key : dataSourceMaps.keySet()) {
            DynamicDataSourceContextHolder.dataSourceIds.add(key);
        }

        // 創建DynamicDataSource
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(DynamicDataSource.class);
        beanDefinition.setSynthetic(true);

        MutablePropertyValues mutablePropertyValues = beanDefinition.getPropertyValues();
        mutablePropertyValues.addPropertyValue("defaultTargetDataSource", defaultDataSource);
        mutablePropertyValues.addPropertyValue("targetDataSources", targetDataSources);
        beanDefinitionRegistry.registerBeanDefinition("dataSource", beanDefinition);
    }
}


好了,這么一坨代碼丟在這兒,相信讀者也看著費勁,接下來對動態數據源注冊器略作解釋

EnvironmentAware接口提供了一個setEnvironment(Environment environment)方法,通過這個方法我們可以從application.properties配置文件中獲取到所有數據源的配置信息,然后創建數據源并加載到內存中

ImportBeanDefinitionRegistrar接口,光看接口名字大概都能猜到是做什么的,對,就是注冊Bean的。該接口用于在系統處理@Configuration class時注冊更多的bean。是bean定義級別的操作,而非@Bean method/instance級別的。該接口提供了registerBeanDefinitions方法,該方法是在Spring加載bean時被Spring調用。通過setEnvironment方法,已經將配置文件中所有的數據源獲取到了,然后在registerBeanDefinitions方法中將所有數據源注冊到Spring容器中。

5、將動態數據源注冊器導入到Spring容器中

    @SpringBootApplication
    @Import({DynamicDataSourceRegister.class})
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }

需要注意的是,使用@Import導入的類必須滿足符合以下的某一個條件:

  1. 導入的類使用@Configuration進行標注
  2. 導入的類中至少有一個使用@Bean標準的方法
  3. 導入的類實現了ImportSelector接口
  4. 導入的類實現了ImportBeanDefinitionRegistrar接口

到這一步了,是不是就完了呢,當然不是,以上這些步驟只是為切換數據源提供了基礎

  • 6、新建一個TargetDataSource注解
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface TargetDataSource {
        String value();
    }

此注解用來標記當前的方法的數據源的,在需要指定數據源的方法上標記@TargetDataSource("AAA")注解即可,還沒完,繼續往下看。

  • 7、新建數據源切換AOP切面
@Aspect
@Order(-1)  //保證此AOP在@Transactional之前執行
@Component
public class DynamicDataSourceAspect {

    private transient static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    // 通過注解切換數據源(細粒度)
    @Around("@annotation(targetDataSource)")
    public Object changeDataSource(ProceedingJoinPoint joinPoint, TargetDataSource targetDataSource) throws Throwable {
        Object object = null;
        String dataSourceId = targetDataSource.value();
        if(DynamicDataSourceContextHolder.containsDataSource(dataSourceId)) {
            logger.info("系統將使用{}數據源", dataSourceId);
            DynamicDataSourceContextHolder.setDataSource(dataSourceId);
        } else {
            logger.debug("數據源{}不存在,將使用默認數據源{}", dataSourceId, joinPoint.getSignature());
        }
        object=joinPoint.proceed();
        DynamicDataSourceContextHolder.clearDataSource();
        return object;
    }

}

解釋解釋,這個切面呢,就是切標記了targetDataSource注解的方法,根據targetDataSource注解的value值設置系統當前的數據源。使用注解方式算是一種細粒度的控制,可切換多個數據源;粗粒度的就是直接切某一個包路徑,而且只能是兩個數據源互切。兩種方式各有各的好處,看業務需要。不過總的來說,能解決問題的方法就是好方法。

最后附一下JNDI數據源在application.properties文件中的配置

    spring.datasource.jndi-name=java:comp/env/jdbc/AAA,java:comp/env/jdbc/BBB

其實,JNDI數據源也可以直接配置到application.properties文件中,或者兩種模式都支持,此處不做累述。

------------------------------------------------華麗的分割線----------------------------------------------------

在項目的進展中,此數據源切換已被改造,增加了Druid數據源加密功能,因為是多數據源加密,和官網的有些不一樣,代碼就不一一累述,讀者若有需要,可自行研究或聯系博主獲取


關注我的微信公眾號:FramePower
我會不定期發布相關技術積累,歡迎對技術有追求、志同道合的朋友加入,一起學習成長!


微信公眾號
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容