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

目录

  • 一、yml配置
  • 二、动态切换数据源配置文件
    • 1.数据源db1
    • 2.数据源db2
  • 三、多数据源的mapper包最好是分开
    • 四、代码中调用
      • 总结
        进行动态切换,需要在类里面配置,顺便解决mybatis-plus自带代码无法使用问题,直接上代码:
        【使用springboot+druid双数据源动态配置操作】
        一、yml配置 数据源可以都是oracle的也可以一个是oracle一个是mysql的。
        spring:datasource:druid:db-type: com.alibaba.druid.pool.DruidDataSource#多数据源1:zjdb:driverClassName: oracle.jdbc.driver.OracleDriverurl: jdbc:oracle:thin:@XX.XX.XX.XX:1521/ORCLusername: XXXXXXXpassword: XXX# \u521D\u59CB\u5316\u8FDE\u63A5\u5927\u5C0Finitial-size: 5# \u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5\u6570min-idle: 5max-active: 20max-wait: 30000# \u53EF\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\u95F4\u9694\u65F6\u95F4time-between-eviction-runs-millis: 60000# \u914D\u7F6E\u8FDE\u63A5\u5728\u6C60\u4E2D\u7684\u6700\u5C0F\u751F\u5B58\u65F6\u95F4min-evictable-idle-time-millis: 300000validation-query: select '1' from dualtest-while-idle: truetest-on-borrow: falsetest-on-return: false# \u6253\u5F00PSCache\uFF0C\u5E76\u4E14\u6307\u5B9A\u6BCF\u4E2A\u8FDE\u63A5\u4E0APSCache\u7684\u5927\u5C0Fpool-prepared-statements: truemax-open-prepared-statements: 20max-pool-prepared-statement-per-connection-size: 20# \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filtersfilters: stat #多数据源2:zjfz:driverClassName: oracle.jdbc.driver.OracleDriverurl: jdbc:oracle:thin:@XX.XX.XX.XX:51521/ORCLusername: XXXXXpassword: 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\u5C0Finitial-size: 5# \u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5\u6570min-idle: 5max-active: 20max-wait: 30000# \u53EF\u5173\u95ED\u7684\u7A7A\u95F2\u8FDE\u63A5\u95F4\u9694\u65F6\u95F4time-between-eviction-runs-millis: 60000# \u914D\u7F6E\u8FDE\u63A5\u5728\u6C60\u4E2D\u7684\u6700\u5C0F\u751F\u5B58\u65F6\u95F4min-evictable-idle-time-millis: 300000validation-query: select '1' from dualtest-while-idle: truetest-on-borrow: falsetest-on-return: false# \u6253\u5F00PSCache\uFF0C\u5E76\u4E14\u6307\u5B9A\u6BCF\u4E2A\u8FDE\u63A5\u4E0APSCache\u7684\u5927\u5C0Fpool-prepared-statements: truemax-open-prepared-statements: 20max-pool-prepared-statement-per-connection-size: 20# \u914D\u7F6E\u76D1\u63A7\u7EDF\u8BA1\u62E6\u622A\u7684filtersfilters: stat stat-view-servlet:url-pattern: /druid/*reset-enable: falselogin-username: adminlogin-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 而不是 SqlSessionFactoryBeanMybatisSqlSessionFactoryBean 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 {// 使用上面配置的FactorySqlSessionTemplate 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 {// 使用上面配置的FactorySqlSessionTemplate template = new SqlSessionTemplate(zjfzSqlSessionFactory); return template; }}


        三、多数据源的mapper包最好是分开 在扫描的时候会动态注入,可能在上述代码中会导致数据源自动切换失败:
        使用springboot+druid双数据源动态配置操作
        文章图片


        四、代码中调用 使用springboot+druid双数据源动态配置操作
        文章图片


        总结
        • 1. 注意动态配置的类结合自己的包项目结构修改
        • 2. 解决了mybatis-plus自带语句不能使用问题
        • 3. 解决无法使用分页问题
        • 4. 解决无法使用oracle自增主键问题
        以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

          推荐阅读