1. 程式人生 > >Spring boot 基於註解的的多資料來源切換

Spring boot 基於註解的的多資料來源切換

一.建立以下類


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


/**
 * 動態資料來源
 *
 * @author liwc
 * @version V1.0
 * @date 2018/4/23 21:38
 */
public class DynamicDataSource extends AbstractRoutingDataSource {
    /**
     * 程式碼中的determineCurrentLookupKey方法取得一個字串,
     * 該字串將與配置檔案中的相應字串進行匹配以定位資料來源,配置檔案
     *即applicationContext.xml檔案中需要要如下程式碼
     */
    @Override
    protected Object determineCurrentLookupKey() {
        /**
         * DynamicDataSourceContextHolder程式碼中使用setDataSourceType
         * 設定當前的資料來源,在路由類中使用getDataSourceType進行獲取,
         *  交給AbstractRoutingDataSource進行注入使用。
         */
        return DynamicDataSourceContextHolder.getDataSourceType();


    }
}


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


import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


/**
 * 切面
 * @Order(-5)保證該AOP在@Transactional之前執行
 *
 * @author liwc
 * @version V1.0
 * @date 2018/4/23 21:40
 */
@Aspect
@Order(-5)
@Component
public class DynamicDataSourceAspect {


    private static Logger logger = LogManager.getLogger(DynamicDataSourceAspect.class.getName());


    /**
     * @Before("@annotation(ds)") 的意思是:
     * @Before:在方法執行之前進行執行:
     * @annotation(targetDataSource): 會攔截註解targetDataSource的方法,否則不攔截;
     */
    @Before("@annotation(targetDataSource)")
    public void changeDataSource(JoinPoint point, TargetDataSource targetDataSource) throws Throwable {
        //獲取當前的指定的資料來源;
        String dsId = targetDataSource.value();
        //如果不在我們注入的所有的資料來源範圍之內,那麼輸出警告資訊,系統自動使用預設的資料來源。
        if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
            logger.debug("資料來源[{}]不存在,使用預設資料來源 > {}" + targetDataSource.value() + point.getSignature());
        } else {
            logger.debug("Use DataSource : {} > {}" + targetDataSource.value() + point.getSignature());
            //找到的話,那麼設定到動態資料來源上下文中。
            DynamicDataSourceContextHolder.setDataSourceType(targetDataSource.value());
        }
    }


    @After("@annotation(targetDataSource)")
    public void restoreDataSource(JoinPoint point, TargetDataSource targetDataSource) {
        logger.debug("Revert DataSource : {} > {}" + targetDataSource.value() + point.getSignature());
        //方法執行完畢之後,銷燬當前資料來源資訊,進行垃圾回收。
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}


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


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


/**
 * 動態資料來源上下文
 *
 * @author liwc
 * @version V1.0
 * @date 2018/4/23 21:36
 */
public class DynamicDataSourceContextHolder {


    /**
     * 當使用ThreadLocal維護變數時,ThreadLocal為每個使用該變數的執行緒提供獨立的變數副本,
     * 所以每一個執行緒都可以獨立地改變自己的副本,而不會影響其它執行緒所對應的副本。
     */
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();


    /**
     * 管理所有的資料來源id
     * 主要是為了判斷資料來源是否存在
     */
    public static List<String> dataSourceIds = new ArrayList<String>();


    /**
     * 使用setDataSourceType設定當前的
     *
     * @param dataSourceType
     */
    public static void setDataSourceType(String dataSourceType) {
        contextHolder.set(dataSourceType);
    }
    public static String getDataSourceType() {
        return contextHolder.get();
    }
    public static void clearDataSourceType() {
        contextHolder.remove();
    }
    /**
     * 判斷指定DataSource當前是否存在
     *
     */
    public static boolean containsDataSource(String dataSourceId) {
        return dataSourceIds.contains(dataSourceId);
    }
}


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


import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.bind.RelaxedDataBinder;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotationMetadata;


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


/**
 * 動態資料來源註冊
 *
 * @author liwc
 * @version V1.0
 * @date 2018/4/23 21:43
 */
public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {


    private static Logger logger = LogManager.getLogger(DynamicDataSourceRegister.class.getName());




    private static final Object DATASOURCE_TYPE_DEFAULT = "org.apache.tomcat.jdbc.pool.DataSource";
    private ConversionService conversionService = new DefaultConversionService();
    private PropertyValues dataSourcePropertyValues;
    /**
     * 預設資料來源
     */
    private DataSource defaultDataSource;
    private Map<String, DataSource> customDataSources = new HashMap<String, DataSource>();


    /**
     * 載入多資料來源配置
     */
    @Override
    public void setEnvironment(Environment environment) {
        initDefaultDataSource(environment);
        initCustomDataSources(environment);
    }


    /**
     * 載入主資料來源配置.
     *
     * @param env
     */
    private void initDefaultDataSource(Environment env) {
        // 讀取主資料來源
        RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
        Map<String, Object> dsMap = new HashMap<String, Object>();
        dsMap.put("type", propertyResolver.getProperty("type"));
        dsMap.put("driverClassName", propertyResolver.getProperty("driverClassName"));
        dsMap.put("url", propertyResolver.getProperty("url"));
        dsMap.put("username", propertyResolver.getProperty("username"));
        dsMap.put("password", propertyResolver.getProperty("password"));
        //建立資料來源
        defaultDataSource = buildDataSource(dsMap);
        dataBinder(defaultDataSource, env);
    }


    /**
     * 初始化更多資料來源
     *
     * @author SHANHY
     * @create 2016年1月24日
     */
    private void initCustomDataSources(Environment env) {
        // 讀取配置檔案獲取更多資料來源,也可以通過defaultDataSource讀取資料庫獲取更多資料來源
        RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "custom.datasource.");
        String dsPrefixs = propertyResolver.getProperty("names");
        // 多個數據源
        for (String dsPrefix : dsPrefixs.split(",")) {
            Map<String, Object> dsMap = propertyResolver.getSubProperties(dsPrefix + ".");
            DataSource ds = buildDataSource(dsMap);
            customDataSources.put(dsPrefix, ds);
            dataBinder(ds, env);
        }
    }


    /**
     * 建立datasource.
     *
     * @param dsMap
     * @return
     */
    public DataSource buildDataSource(Map<String, Object> dsMap) {
        Object type = dsMap.get("type");
        if (type == null) {
            // 預設DataSource
            type = DATASOURCE_TYPE_DEFAULT;
        }
        Class<? extends DataSource> dataSourceType;
        try {
            dataSourceType = (Class<? extends DataSource>) Class.forName((String) type);
            String driverClassName = dsMap.get("driverClassName").toString();
            String url = dsMap.get("url").toString();
            String username = dsMap.get("username").toString();
            String password = dsMap.get("password").toString();
            DataSourceBuilder factory = DataSourceBuilder.create().driverClassName(driverClassName).url(url).username(username).password(password).type(dataSourceType);
            return factory.build();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 為DataSource繫結更多資料
     * @param dataSource
     * @param env
     */
    private void dataBinder(DataSource dataSource, Environment env) {
        RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);
        dataBinder.setConversionService(conversionService);
        dataBinder.setIgnoreNestedProperties(false);
        dataBinder.setIgnoreInvalidFields(false);
        dataBinder.setIgnoreUnknownFields(true);
        if (dataSourcePropertyValues == null) {
            Map<String, Object> rpr = new RelaxedPropertyResolver(env, "spring.datasource").getSubProperties(".");
            Map<String, Object> values = new HashMap<>(rpr);
            // 排除已經設定的屬性
            values.remove("type");
            values.remove("driverClassName");
            values.remove("url");
            values.remove("username");
            values.remove("password");
            dataSourcePropertyValues = new MutablePropertyValues(values);
        }
        dataBinder.bind(dataSourcePropertyValues);
    }


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        logger.debug("註冊資料來源: DynamicDataSourceRegister.registerBeanDefinitions()");
        Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
        // 將主資料來源新增到更多資料來源中
        targetDataSources.put("dataSource", defaultDataSource);
        DynamicDataSourceContextHolder.dataSourceIds.add("dataSource");
        // 新增更多資料來源
        targetDataSources.putAll(customDataSources);
        for (String key : customDataSources.keySet()) {
            DynamicDataSourceContextHolder.dataSourceIds.add(key);
        }
        // 建立DynamicDataSource
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClass(DynamicDataSource.class);
        beanDefinition.setSynthetic(true);
        MutablePropertyValues mpv = beanDefinition.getPropertyValues();
        //新增屬性:AbstractRoutingDataSource.defaultTargetDataSource
        mpv.addPropertyValue("defaultTargetDataSource", defaultDataSource);
        mpv.addPropertyValue("targetDataSources", targetDataSources);
        registry.registerBeanDefinition("dataSource", beanDefinition);
    }
}


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


import java.lang.annotation.*;


/**
 * 自定義註解,資料來源指定
 * @author
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
    String value();
}


============================================================================================================


2.配置檔案


#主資料來源配置資訊
  datasource:
      url : jdbc:mysql://ip:port/dateBaseName
      username : root
      password : root
      driverClassName : com.mysql.jdbc.Driver


#Druid配置
      #連線型別
      type : com.alibaba.druid.pool.DruidDataSource
      # 初始化大小,最小,最大
      initialSize : 10
      #最小空閒連線數
      minIdle : 0
      #最大併發連線數
      maxActive : 1000
      # 配置獲取連線等待超時的時間
      maxWait : 60000
      # 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連線,單位是毫秒
      timeBetweenEvictionRunsMillis : 60000
      # 配置一個連線在池中最小生存的時間,單位是毫秒
      minEvictableIdleTimeMillis : 300000
      #用來檢測連線是否有效的sql,要求是一個查詢語句
      validationQuery : SELECT 1 FROM sys_role
      #建議配置為true,不影響效能,並且保證安全性。
      #申請連線的時候檢測,如果空閒時間大於
      #timeBetweenEvictionRunsMillis,
      #執行validationQuery檢測連線是否有效。
      testWhileIdle : true
      #申請連線時執行validationQuery檢測連線是否有效,做了這個配置會降低效能。
      testOnBorrow : false
      #歸還連線時執行validationQuery檢測連線是否有效,做了這個配置會降低效能
      testOnReturn : false
      #是否快取preparedStatement,也就是PSCache。
      #PSCache對支援遊標的資料庫效能提升巨大,比如說oracle。
      #在mysql5.5以下的版本中沒有PSCache功能,建議關閉掉。
      #該應該是支援PSCache。
      poolPreparedStatements : true
      # 配置監控統計攔截的filters監控統計用的filter:stat
      #日誌用的filter:log4j
      #防禦sql注入的filter:wall
      filters : stat,wall,log4j
      # 通過connectProperties屬性來開啟mergeSql功能;慢SQL記錄
      connectionProperties : druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000


#自定義資料來源配置資訊
custom:
  datasource:
    names: ds1,ds2
    ds1:


      url: jdbc:sqlserver://ip:port;DatabaseName=xxx
      username: root
      password: root
      driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver


    ds2:


      url: jdbc:oracle:thin:@host:port:SID | jdbc:oracle:thin:@//host:port/service_name | jdbc:oracle:thin:@TNSName 
      username: root
      password: root
      driverClassName: oracle.jdbc.driver.OracleDriver


============================================================================================================


@Override
    @TargetDataSource("ds1")
    public List<Object> findOrderCountResult(String beginStationUuid, String endStationUuid, Integer dayType, Integer rowType)  {
       //資料持久化
    }