springboot+druid双数据源动态配置

springboot+druid双数据源动态配置

进行动态切换,需要在类里面配置,顺便解决mybatis-plus自带代码无法使用问题,直接上代码:

一.yml配置:

数据源可以都是oracle的也可以一个是oracle一个是mysql的。

spring:
  datasource:
    druid:
      db-type: com.alibaba.druid.pool.DruidDataSource
    #多数据源1:
    zjdb:
      driverClassName: oracle.jdbc.driver.OracleDriver
      url: jdbc:oracle:thin:@XX.XX.XX.XX:1521/ORCL
      username: XXXXXXX
      password: XXX
      # \u521D\u59CB\u5316\u8FDE\u63A5\u5927\u5C0F
      initial-size: 5
      # \u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5\u6570
      min-idle: 5
      max-active: 20
      max-wait: 30000
      # \u53EF\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\u95F4\u9694\u65F6\u95F4
      time-between-eviction-runs-millis: 60000
      # \u914D\u7F6E\u8FDE\u63A5\u5728\u6C60\u4E2D\u7684\u6700\u5C0F\u751F\u5B58\u65F6\u95F4
      min-evictable-idle-time-millis: 300000
      validation-query: select '1' from dual
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # \u6253\u5F00PSCache\uFF0C\u5E76\u4E14\u6307\u5B9A\u6BCF\u4E2A\u8FDE\u63A5\u4E0APSCache\u7684\u5927\u5C0F
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      max-pool-prepared-statement-per-connection-size: 20
      # \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters
      filters: stat

    #多数据源2:
    zjfz:
      driverClassName: oracle.jdbc.driver.OracleDriver
      url: jdbc:oracle:thin:@XX.XX.XX.XX:51521/ORCL
      username: XXXXX
      password: XXXX
#      driverClassName: com.mysql.jdbc.Driver
#      url: jdbc:mysql://127.0.0.1:3306/ketech-dev?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&allowMultiQueries=true&allowPublicKeyRetrieval=true
#      username: root
#      password: 123456
      # \u521D\u59CB\u5316\u8FDE\u63A5\u5927\u5C0F
      initial-size: 5
      # \u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5\u6570
      min-idle: 5
      max-active: 20
      max-wait: 30000
      # \u53EF\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\u95F4\u9694\u65F6\u95F4
      time-between-eviction-runs-millis: 60000
      # \u914D\u7F6E\u8FDE\u63A5\u5728\u6C60\u4E2D\u7684\u6700\u5C0F\u751F\u5B58\u65F6\u95F4
      min-evictable-idle-time-millis: 300000
      validation-query: select '1' from dual
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      # \u6253\u5F00PSCache\uFF0C\u5E76\u4E14\u6307\u5B9A\u6BCF\u4E2A\u8FDE\u63A5\u4E0APSCache\u7684\u5927\u5C0F
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      max-pool-prepared-statement-per-connection-size: 20
      # \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filters
      filters: stat

      stat-view-servlet:
        url-pattern: /druid/*
        reset-enable: false
        login-username: admin
        login-password: 123456

      web-stat-filter:
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"

二:动态切换数据源配置文件

1.数据源db1:

package yin.ketech.app.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @FileName: ZjDbConfig
 * @Author Yep
 * @create 2020-06-17
 * @Description: 多数据源-1
 */

@Configuration
@MapperScan(basePackages = "yin.ketech.app.mapper", sqlSessionFactoryRef = "zjdbSqlSessionFactory")
public class ZjDbConfig {

    @Primary
    @Bean(name = "zjdbDataSource")
    @Qualifier("zjdbDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.zjdb")
    public DataSource zjdbDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "zjdbSqlSessionFactory")
    @Qualifier("zjdbSqlSessionFactory")
    public SqlSessionFactory zjdbSqlSessionFactory(@Qualifier("zjdbDataSource") DataSource zjdbDataSource) throws Exception {
//        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
//        factoryBean.setDataSource(zjdbDataSource);
        //解决无法使用自带方法问题
        // TODO 使用 MybatisSqlSessionFactoryBean 而不是 SqlSessionFactoryBean
        MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
        factory.setDataSource(zjdbDataSource);
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            factory.setMapperLocations(resolver.getResources("classpath:/yin/ketech/app/mapper/*/*.xml"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        //解决无法使用分页问题
//        factory.setPlugins(new Interceptor[]{new MybatisPlusConfig().paginationInterceptor()});
        //设置Oracle主键自增
        factory.setGlobalConfig(new MybatisPlusConfig().globalConfig());
        return factory.getObject();
    }

    @Primary
    @Bean(name = "zjdbSqlSessionTemplate")
    public SqlSessionTemplate zjdbSqlSessionTemplate(@Qualifier("zjdbSqlSessionFactory") SqlSessionFactory zjdbSqlSessionFactory) throws Exception {
        // 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(zjdbSqlSessionFactory);
        return template;
    }
    
}

2..数据源db2:

package yin.ketech.app.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @FileName: ZjFzConfig
 * @Author Yep
 * @create 2020-06-17
 * @Description: 多数据源-2
 */

@Configuration
@MapperScan(basePackages = "yin.ketech.app.zjfzmapper", sqlSessionFactoryRef = "zjfzSqlSessionFactory")
public class ZjFzConfig {


    @Bean(name = "zjfzDataSource")
    @Qualifier("zjfzDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.zjfz")
    public DataSource zjfzDataSource() {
        return DruidDataSourceBuilder.create().build();
    }


    @Bean(name = "zjfzSqlSessionFactory")
    @Qualifier("zjfzSqlSessionFactory")
    public SqlSessionFactory zjfzSqlSessionFactory(@Qualifier("zjfzDataSource") DataSource zjfzDataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(zjfzDataSource);
        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            factoryBean.setMapperLocations(resolver.getResources("classpath:/yin/ketech/app/mapper/zjfz/mapper/*.xml"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return factoryBean.getObject();
    }


    @Bean(name = "zjfzSqlSessionTemplate")
    public SqlSessionTemplate zjfzSqlSessionTemplate(@Qualifier("zjfzSqlSessionFactory") SqlSessionFactory zjfzSqlSessionFactory) throws Exception {
        // 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(zjfzSqlSessionFactory);
        return template;
    }
}

三:多数据源的mapper包最好是分开,在扫描的时候会动态注入,可能在上述代码中会导致数据源自动切换失败:

四:代码中调用:

总结:

 1.注意动态配置的类结合自己的包项目结构修改

  2.解决了mybatis-plus自带语句不能使用问题

  3.解决无法使用分页问题

  4.解决无法使用oracle自增主键问题

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Java大表哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值