SpringBoot 多数据源

(1)DynamicDataSource 类继承AbstractRoutingDataSource


package com.bootdo.common.dataSourseConfig;



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


public class DynamicDataSource extends AbstractRoutingDataSource {


     /*


     * 代码中的determineCurrentLookupKey方法取得一个字符串,


     * 该字符串将与配置文件中的相应字符串进行匹配以定位数据源,配置文件,即applicationContext.xml文件中需要要如下代码:(non-Javadoc)


     * @see org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineCurrentLookupKey()


     */


    @Override


    protected Object determineCurrentLookupKey() {


       /*


        * DynamicDataSourceContextHolder代码中使用setDataSourceType


        * 设置当前的数据源,在路由类中使用getDataSourceType进行获取,


        *  交给AbstractRoutingDataSource进行注入使用。


        */


        return DynamicDataSourceContextHolder.getDataSourceType();


    }
}



(2)DynamicDataSourceContextHolder  使用ThreadLocal 维护DataSourceType


package com.bootdo.common.dataSourseConfig;


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


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();


    }




    /**
     * 判断指定DataSrouce当前是否存在
     *
     * @param dataSourceId
     * @return
     * @author SHANHY
     * @create 2016年1月24日
     */


    public static boolean containsDataSource(String dataSourceId) {


        return dataSourceIds.contains(dataSourceId);


    }
}



(3)DynamicDataSourceRegister  配置数据源

package com.bootdo.common.dataSourseConfig;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


import javax.sql.DataSource;


import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
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 com.alibaba.druid.pool.DruidDataSource;


public class DynamicDataSourceRegister implements ImportBeanDefinitionRegistrar, EnvironmentAware {
    //如配置文件中未指定数据源类型,使用该默认值
	//druid 属性配置-------------------------
	private int initialSize;
    private int minIdle;
    private int maxActive;
    private long maxWait;
    private long timeBetweenEvictionRunsMillis;
    private long minEvictableIdleTimeMillis;
    private String validationQuery;
    private boolean testWhileIdle;
    private boolean testOnBorrow;
    private boolean testOnReturn;
    private boolean poolPreparedStatements;
    private int maxPoolPreparedStatementPerConnectionSize;
    private String filters;
    private String connectionProperties;
  //druid 属性配置-------------------------
	
    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) {   //1


        System.out.println("DynamicDataSourceRegister.setEnvironment()");


        initDruidProperties(environment);
        
        initDefaultDataSource(environment);


        initCustomDataSources(environment);


    }
    
    /**
     * 加载druid据源配置.
     *
     * @param env
     */
    private void initDruidProperties(Environment env) {  //2
        RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
        initialSize = Integer.parseInt(propertyResolver.getProperty("initialSize"));
        minIdle = Integer.parseInt(propertyResolver.getProperty("minIdle"));
        maxActive = Integer.parseInt(propertyResolver.getProperty("maxActive"));
        maxWait = Long.parseLong(propertyResolver.getProperty("maxWait"));
        timeBetweenEvictionRunsMillis = Long.parseLong(propertyResolver.getProperty("timeBetweenEvictionRunsMillis"));
        minEvictableIdleTimeMillis = Long.parseLong(propertyResolver.getProperty("minEvictableIdleTimeMillis"));
        validationQuery = propertyResolver.getProperty("validationQuery");
        testWhileIdle = Boolean.parseBoolean(propertyResolver.getProperty("testWhileIdle"));
        testOnBorrow = Boolean.parseBoolean(propertyResolver.getProperty("testOnBorrow"));
        testOnReturn = Boolean.parseBoolean(propertyResolver.getProperty("testOnReturn"));
        poolPreparedStatements = Boolean.parseBoolean(propertyResolver.getProperty("poolPreparedStatements"));
        maxPoolPreparedStatementPerConnectionSize = Integer.parseInt(propertyResolver.getProperty("maxPoolPreparedStatementPerConnectionSize"));
        filters = propertyResolver.getProperty("filters");
        connectionProperties = propertyResolver.getProperty("connectionProperties");
    }


    /**
     * 加载主数据源配置.
     *
     * @param env
     */


    private void initDefaultDataSource(Environment env) {  //3


        // 读取主数据源

        //为简便Druid 配置就放在主配置下了,为了规范也可以另起一套配置放在 "Druid."下  
        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) {  //6


        // 读取配置文件获取更多数据源,也可以通过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
     */


    @SuppressWarnings("unchecked")


    public DataSource buildDataSource(Map<String, Object> dsMap) {  //4    //7   //9


        Object type = dsMap.get("type");


        if (type == null) {


            type = DATASOURCE_TYPE_DEFAULT;// 默认DataSource


        }


        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();


            DruidDataSource druidDataSource = new DruidDataSource();
            druidDataSource.setDriverClassName(driverClassName);
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);


            druidDataSource.setInitialSize(initialSize);
            druidDataSource.setMinIdle(minIdle);
            druidDataSource.setMaxActive(maxActive);
            druidDataSource.setMaxWait(maxWait);
            druidDataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
            druidDataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
            druidDataSource.setValidationQuery(validationQuery);
            druidDataSource.setTestWhileIdle(testWhileIdle);
            druidDataSource.setTestOnBorrow(testOnBorrow);
            druidDataSource.setTestOnReturn(testOnReturn);
            druidDataSource.setPoolPreparedStatements(poolPreparedStatements);
            druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
            druidDataSource.setConnectionProperties(connectionProperties);
            
            try {
                druidDataSource.setFilters(filters);
                druidDataSource.init();
            } catch (SQLException e) {
                e.printStackTrace();
            }


            return druidDataSource;
            
            // 不使用 druid
//            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) {//5    //8     //10


        RelaxedDataBinder dataBinder = new RelaxedDataBinder(dataSource);


        dataBinder.setConversionService(conversionService);


        dataBinder.setIgnoreNestedProperties(false);//false


        dataBinder.setIgnoreInvalidFields(false);//false


        dataBinder.setIgnoreUnknownFields(true);//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) {  //11


        System.out.println("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);
        
        System.out.println("==============");


    }
}


(4)TargetDataSource  注解(通过注解来调用数据源)

package com.bootdo.common.dataSourseConfig.annotation;


import java.lang.annotation.*;


@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
    String value();
}

(5)DynamicDataSourceAspect  (通过AOP来实现注解切换数据源)

package com.bootdo.common.dataSourseConfig.aop;




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;


import com.bootdo.common.dataSourseConfig.DynamicDataSourceContextHolder;
import com.bootdo.common.dataSourseConfig.annotation.TargetDataSource;


@Aspect
@Order(-10)//保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {
    /*


     * @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)) {


            System.err.println("数据源[{}]不存在,使用默认数据源 > {}" + targetDataSource.value() + point.getSignature());


        } else {


            System.out.println("Use DataSource : {} > {}" + targetDataSource.value() + point.getSignature());


            //找到的话,那么设置到动态数据源上下文中。


            DynamicDataSourceContextHolder.setDataSourceType(targetDataSource.value());


        }


    }




    @After("@annotation(targetDataSource)")
    public void restoreDataSource(JoinPoint point, TargetDataSource targetDataSource) {


        System.out.println("Revert DataSource : {} > {}" + targetDataSource.value() + point.getSignature());


        //方法执行完毕之后,销毁当前数据源信息,进行垃圾回收。


        DynamicDataSourceContextHolder.clearDataSourceType();


    }
}


(6)BootdoApplication 

package com;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;


import com.bootdo.common.dataSourseConfig.DynamicDataSourceRegister;
//开启事务功能  开启事务支持后,然后在访问数据库的Service方法上添加注解 @Transactional 便可。
@EnableTransactionManagement
@ServletComponentScan
@MapperScan("com.bootdo.*.dao")
//@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class})
@SpringBootApplication
@EnableCaching
@Import({DynamicDataSourceRegister.class})
public class BootdoApplication {
    public static void main(String[] args) {
        SpringApplication.run(BootdoApplication.class, args);
        
    }
}
package com.bootdo.common.dataSourseConfig.annotation;


import java.lang.annotation.*;


@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
    String value();
}


配置文件:xxxxx.yml

bootdo:
  uploadPath: x:/xx/xxx/
logging:
  level:
    root: info
    com.bootdo: debug
spring:
  application:
    name: data-multidatasource
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.jdbc.Driver
    url: jdbc:mysql://xxxxxxxxx:3306/xxxx?useUnicode=true&characterEncoding=utf8
    username: root
    password: root
    initialSize: 1
    minIdle: 3
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 30000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    # 打开PSCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合并多个DruidDataSource的监控数据
    #useGlobalDataSourceStat: true
  redis:
      host: localhost
      port: 6379
      password:
      # 连接超时时间(毫秒)
      timeout: 10000
      pool:
        # 连接池中的最大空闲连接
        max-idle: 8
        # 连接池中的最小空闲连接
        min-idle: 10
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 100
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1
        
custom:
  datasource:
    names: ds1,ds2
    ds1:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://xxxxxxxxx:3306/xxxx?useUnicode=true&characterEncoding=utf8
      username: root
      password: root
      
    ds2:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://xxxxxxxxx:3306/xxxxx?useUnicode=true&characterEncoding=utf8
      username: root
      password: root
      
      

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值