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)  {
       //数据持久化
    }

猜你喜欢

转载自blog.csdn.net/echizao1839/article/details/80336306