服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 使用springboot+druid双数据源动态配置操作

使用springboot+druid双数据源动态配置操作

2021-12-22 13:07Java大表哥 Java教程

这篇文章主要介绍了使用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包最好是分开

在扫描的时候会动态注入,可能在上述代码中会导致数据源自动切换失败:

使用springboot+druid双数据源动态配置操作

 

四、代码中调用

使用springboot+druid双数据源动态配置操作

 

总结

  • 1. 注意动态配置的类结合自己的包项目结构修改
  • 2. 解决了mybatis-plus自带语句不能使用问题
  • 3. 解决无法使用分页问题
  • 4. 解决无法使用oracle自增主键问题

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/erpenggg/article/details/106927247

延伸 · 阅读

精彩推荐