spring boot 配置多数据源

  1. 创建boot 项目 导入相关的pom
  2. 在配置文件中 配置 datasource 直接上代码
datasource:
					        type: com.alibaba.druid.pool.DruidDataSource
					        druid:
					            first:  #数据源1
					                driver-Class-Name: com.mysql.jdbc.Driver
					                url: jdbc:mysql://xxx:3306/book?useUnicode=true&characterEncoding=UTF-8
					                username: root
					                password: xxx
					            second:  #数据源2
					                url: jdbc:mysql://xxx:3306/test?useUnicode=true&characterEncoding=UTF-8
					                username: root
					                password: xxx
					                driver-Class-Name: com.mysql.jdbc.Driver
					            third: #数据源3
					                 url: jdbc:mysql://xxxx:3306/student?useUnicode=true&characterEncoding=UTF-8
					                 username: root
					                 password: xxx
					                 driver-Class-Name: com.mysql.jdbc.Driver
					            initial-size: 10
					            max-active: 100
					            min-idle: 10
					            max-wait: 60000
					            pool-prepared-statements: true
					            max-pool-prepared-statement-per-connection-size: 20
					            time-between-eviction-runs-millis: 60000
					            min-evictable-idle-time-millis: 300000
					            validation-query: SELECT 1 FROM DUAL
					            test-while-idle: true
					            test-on-borrow: false
					            test-on-return: false
					            stat-view-servlet:
					                enabled: true
					                url-pattern: /druid/*
					            filter:
					                stat:
					                    log-slow-sql: true
					                    slow-sql-millis: 1000
					                    merge-sql: true
					                wall:
					                    config:
					                        multi-statement-allow: true
					        devtools:
					          restart:
					            enabled: true # 开启SpringBoot内置热部署

其中 first , second , third 是我们需要切换的数据库的自定以名称
3. 添加配置类

/**  1
			 * 增加多数据源,在此配置
			 */
			public interface DataSourceNames {
			    String FIRST = "first";
			    String SECOND = "second";
			    String THIDR = "third";
			}

			/**  2 
			 * 多数据源注解
			 */
			@Target(ElementType.METHOD)
			@Retention(RetentionPolicy.RUNTIME)
			@Documented
			public @interface DataSource {
			    String name() default "";
			}

/** 3

  • 动态数据源

  • @Date: 2018年11月14日
    */
    public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal contextHolder = new ThreadLocal<>();

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
    super.setDefaultTargetDataSource(defaultTargetDataSource);
    super.setTargetDataSources(targetDataSources);
    super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
    return getDataSource();
    }

    public static void setDataSource(String dataSource) {
    contextHolder.set(dataSource);
    }

    public static String getDataSource() {
    return contextHolder.get();
    }

    public static void clearDataSource() {
    contextHolder.remove();
    }

}

/**

  • 配置多数据源

  • @Date: 2018年11月14日
    */
    @Configuration
    public class DynamicDataSourceConfig {

    // 数据源 1
    @Bean
    @ConfigurationProperties(“spring.datasource.druid.first”)
    public DataSource firstDataSource() {
    return DruidDataSourceBuilder.create().build();
    }

    // 数据源 2
    @Bean
    @ConfigurationProperties(“spring.datasource.druid.second”)
    public DataSource secondDataSource() {
    return DruidDataSourceBuilder.create().build();
    }

    // 数据源 3 添加
    @Bean
    @ConfigurationProperties(“spring.datasource.druid.third”)
    public DataSource thirdDataSource() {
    return DruidDataSourceBuilder.create().build();
    }

    @Bean
    // 必须要有依赖关系 添加数据源
    @DependsOn({“firstDataSource”, “secondDataSource”,“thirdDataSource”})
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource,DataSource thirdDataSource) {
    Map<Object, Object> targetDataSources = new HashMap<>();
    targetDataSources.put(DataSourceNames.FIRST, firstDataSource);
    targetDataSources.put(DataSourceNames.SECOND, secondDataSource);
    targetDataSources.put(DataSourceNames.THIDR, thirdDataSource);
    return new DynamicDataSource(firstDataSource, targetDataSources);
    }

}

/**

  • 多数据源,切面处理类 处理带有注解的方法类
    */
    @Aspect
    @Component
    public class DataSourceAspect implements Ordered {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("@annotation(com.xtd.config.DataSource.DataSource)")//注意:这里的xxxx代表的是上面public @interface DataSource这个注解DataSource的包名
    public void dataSourcePointCut() {

    }

    @Around(“dataSourcePointCut()”)
    public Object around(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    DataSource ds = method.getAnnotation(DataSource.class);
    if (ds == null) {
    DynamicDataSource.setDataSource(DataSourceNames.FIRST);
    logger.debug("set datasource is " + DataSourceNames.FIRST);
    } else {
    DynamicDataSource.setDataSource(ds.name());
    logger.debug("set datasource is " + ds.name());
    }
    try {
    return point.proceed();
    } finally {
    DynamicDataSource.clearDataSource();
    logger.debug(“clean datasource”);
    }
    }

    @Override
    public int getOrder() {
    return 1;
    }
    }

  1. 配置类配置完成以后在持久层使用
    @Override
    @DataSource(name=“first”)
    public List queryAnalysis(Book book) {
    return bookDao.queryAnalysis(book);
    }
    使用 @DataSource(name=“first”)
    name 就是你自定义的数据库名称 随意切换
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值