新的项目需求,需要将子需求A锁定到A库,将子需求B锁定到B库;
就是俗称的“分库”;但这是业务性分库,也就是说,A库和B库并没有任何逻辑上的,主从或水平或垂直分库关系;就是,完全没有关系

思路:

  1. SpringBoot可配置多数据源,但项目中使用Druid进行数据源管理;
  2. 配置好数据源DataSource后,需要将DataSource交给Mybatis的SqlSessionFactory建立相关连接;
  3. 上述两个配置需要结合SpringBoot的@Configuration注解使用,方便简洁;
  4. 多说一句, 整体思路就这么简单, 但细节的修正与项目息息相关, 请各位耐心调试;

实施:

1. yml文件
spring:datasource:type: com.alibaba.druid.pool.DruidDataSourcemaster:driverClassName: com.mysql.jdbc.Driverurl: jdbc:mysql://aaausername: xxxaaapassword: xxxaaareport:driverClassName: com.mysql.jdbc.Driverurl: jdbc:mysql://bbbusername: xxxbbbpassword: xxxbbbinitialSize: 1minIdle: 3maxActive: 20# 配置获取连接等待超时的时间maxWait: 60000# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒timeBetweenEvictionRunsMillis: 60000# 配置一个连接在池中最小生存的时间,单位是毫秒minEvictableIdleTimeMillis: 30000validationQuery: select 'x'testWhileIdle: truetestOnBorrow: falsetestOnReturn: false# 打开PSCache,并且指定每个连接上PSCache的大小poolPreparedStatements: truemaxPoolPreparedStatementPerConnectionSize: 20# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,wall,slf4j# 通过connectProperties属性来打开mergeSql功能;慢SQL记录connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000# 合并多个DruidDataSource的监控数据#useGlobalDataSourceStat: true
2. dataSource-aaa:
package com.project.common.config.datasource;import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
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.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;
import java.sql.SQLException;@SuppressWarnings("AlibabaRemoveCommentedCode")
@MapperScan(basePackages = DruidDBConfig.daoPackages, sqlSessionTemplateRef = "aaaSqlSessionTemplate")
@Configuration
public class DruidDBConfig {public static final String domainPackages = "com.project.**.domain";public static final String daoPackages = "com.project.*.dao";public static final String mapperLocations = "classpath:mybatis/aaa/**/*Mapper.xml";private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);@Value("${spring.datasource.aaa.url}")private String dbUrl;@Value("${spring.datasource.aaa.username}")private String username;@Value("${spring.datasource.aaa.password}")private String password;@Value("${spring.datasource.aaa.driverClassName}")private String driverClassName;@Value("${spring.datasource.initialSize}")private int initialSize;@Value("${spring.datasource.minIdle}")private int minIdle;@Value("${spring.datasource.maxActive}")private int maxActive;@Value("${spring.datasource.maxWait}")private int maxWait;@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")private int timeBetweenEvictionRunsMillis;@Value("${spring.datasource.minEvictableIdleTimeMillis}")private int minEvictableIdleTimeMillis;@Value("${spring.datasource.validationQuery}")private String validationQuery;@Value("${spring.datasource.testWhileIdle}")private boolean testWhileIdle;@Value("${spring.datasource.testOnBorrow}")private boolean testOnBorrow;@Value("${spring.datasource.testOnReturn}")private boolean testOnReturn;@Value("${spring.datasource.poolPreparedStatements}")private boolean poolPreparedStatements;@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")private int maxPoolPreparedStatementPerConnectionSize;@Value("${spring.datasource.filters}")private String filters;@Value("{spring.datasource.connectionProperties}")private String connectionProperties;@Bean(name = "aaaDataSource", initMethod = "init", destroyMethod = "close")   //声明其为Bean实例@Primary  //在同样的DataSource中,首先使用被标注的DataSourcepublic DataSource aaaDataSource() {DruidDataSource datasource = new DruidDataSource();datasource.setUrl(this.dbUrl);datasource.setUsername(username);datasource.setPassword(password);datasource.setDriverClassName(driverClassName);//configurationdatasource.setInitialSize(initialSize);datasource.setMinIdle(minIdle);datasource.setMaxActive(maxActive);datasource.setMaxWait(maxWait);datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);datasource.setValidationQuery(validationQuery);datasource.setTestWhileIdle(testWhileIdle);datasource.setTestOnBorrow(testOnBorrow);datasource.setTestOnReturn(testOnReturn);datasource.setPoolPreparedStatements(poolPreparedStatements);datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);try {datasource.setFilters(filters);} catch (SQLException e) {logger.error("druid configuration initialization filter", e);}datasource.setConnectionProperties(connectionProperties);return datasource;}@Bean(name = "aaaSqlSessionFactory")@Primarypublic SqlSessionFactory aaaSqlSessionFactory(@Qualifier("aaaDataSource") DataSource aaaDataSource) throws Exception {/***!: SqlSessionFactory的配置是重点,详细定制Mybatis针对不同数据源的配置信息,下面几行代码分别配置:1. Entity包名2. DB字段名下划线, 映射成, 驼峰命名法3. Mybatis, Mapper的包所在位置*/SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(aaaDataSource);// 扫描Entitybean.setTypeAliasesPackage(domainPackages);org.apache.ibatis.session.Configuration conf = new org.apache.ibatis.session.Configuration();conf.setMapUnderscoreToCamelCase(true);bean.setConfiguration(conf);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));return bean.getObject();}@Bean(name = "aaaTransactionManager")@Primarypublic DataSourceTransactionManager aaaTransactionManager(@Qualifier("aaaDataSource") DataSource aaaDataSource) {return new DataSourceTransactionManager(aaaDataSource);}@Bean(name = "aaaSqlSessionTemplate")@Primarypublic SqlSessionTemplate aaaSqlSessionTemplate(@Qualifier("aaaSqlSessionFactory") SqlSessionFactory aaaSqlSessionFactory) throws Exception {return new SqlSessionTemplate(aaaSqlSessionFactory);}
}
dataSource-bbb:

bbbaaa配置完全雷同, 可以在上述重点处调整针对不同数据源的SqlSessionFactory细节;

细节与坑:

public static final String domainPackages = "com.project.**.domain";
public static final String daoPackages = "com.project.*.dao";
public static final String mapperLocations = "classpath:mybatis/aaa/**/*Mapper.xml";

mybatis相关的, Entity, Dao, Xml三层, 不同数据源的文件最好放到不同的包里, 做好资源隔离, 相信在调试过程中你会遇到很多资源冲突的bug, 祝好运~

SpringBoot/Mybatis/Druid, 多数据源MultiDataSource配置思路相关推荐

  1. 【daisy-framework】SpringBoot+MyBatis+Druid 多数据源

    前言 Github:https://github.com/yihonglei/daisy-framework/tree/master/daisy-springboot-framework(daisy工 ...

  2. 单手撸了个springboot+mybatis+druid

    本文旨在用最通俗的语言讲述最枯燥的基本知识 最近身边的程序员掀起了学习springboot的热潮,说什么学会了springboot在大街上就可以横着走.什么有了springboot妈妈再也不担心我的编 ...

  3. 3分钟搞定SpringBoot+Mybatis+druid多数据源和分布式事务

    在一些复杂的应用开发中,一个应用可能会涉及到连接多个数据源,所谓多数据源这里就定义为至少连接两个及以上的数据库了. 下面列举两种常用的场景: 一种是读写分离的数据源,例如一个读库和一个写库,读库负责各 ...

  4. 单手撸了个springboot+mybatis+druid 1

    本文旨在用最通俗的语言讲述最枯燥的基本知识 最近身边的程序员掀起了学习springboot的热潮,说什么学会了springboot在大街上就可以横着走.什么有了springboot妈妈再也不担心我的编 ...

  5. 基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建

    首页 Android Java 服务器 标签云 作品 关于 赞助列表  <a href="https://github.com/RayeWang" class="f ...

  6. SpringBoot 优雅实现动态数据源切换配置

    点击关注公众号,利用碎片时间学习 前言 随着应用用户数量的增加,相应的并发请求的数量也会跟着不断增加,慢慢地,单个数据库已经没有办法满足我们频繁的数据库操作请求了,在某些场景下,我们可能会需要配置多个 ...

  7. Springboot+Mybatis+Druid+Maven多模块项目搭建遇到的各种吭

    Springboot+Mybatis+Druid+Maven多模块项目搭建 这里记录一下搭建多模块遇到的吭 首先建立一个父级空项目,在pox里修改下配置 2,建立DaoMapper层和ModelEnt ...

  8. SpringBoot+Mybatis+Druid批量更新 multi-statement not allow异常

    SpringBoot+Mybatis+Druid批量更新 multi-statement not allow异常 参考文章: (1)SpringBoot+Mybatis+Druid批量更新 multi ...

  9. SpringBoot + Mybatis + Druid + PageHelper 实现多数据源并分页

    点击关注公众号,Java干货及时送达 本篇文章主要讲述的是SpringBoot整合Mybatis.Druid和PageHelper 并实现多数据源和分页.其中SpringBoot整合Mybatis这块 ...

最新文章

  1. Vue报错:Uncaught RangeError: Maximum call stack size exceeded
  2. 安装docker之后电脑无法关机
  3. 高校老师暑假狂补AI课背后:AI人才培养竞赛开跑
  4. android 除了webview 浏览器控件,AgentWeb是基于Android WebView一个功能完善小型浏览器库...
  5. 一头扎进sql之多表操作
  6. linux根文件系统的挂载过程详解
  7. DNF私服之PVF修改-装备篇
  8. 万达商管再次递表港交所:上半年净利润40亿元,外部股东阵容强大
  9. 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标
  10. 解决非苹果电脑使用iPad作为扩展屏的问题
  11. 电机控制器培训资料-《如何快准狠的标定永磁同步电机》 品牌:车用电机控制器
  12. ssh 远程报错 Permission denied, please try again.(密码输入正确也无法登录)
  13. 尼古拉·特斯拉——一个比爱迪生更伟大却被世界遗忘的科学巨人
  14. #小何不断努力#8.18
  15. 解决:whm搬站出现的mysql error message:Can't find any matching row in the user table
  16. hive静态与动态分区理解
  17. 有条件的mysql插入语句_mysql中有条件的插入语句
  18. VRTK插件详解四:部分自带案例分析
  19. C# GPIO通道调试(DMCI驱动)
  20. 新概念2 课文和单词(9)

热门文章

  1. 自学计算机该先从什么开始,如何自学,入门推荐学什么语言
  2. nextResponder与Responder Chain
  3. 没有当过一把手的人,很难理解“一把手工程”的说法有多讨厌
  4. 花式拖稿大法,设计师直呼666
  5. sc9832e camera 不能拍RAW图
  6. 中线桩地质体桩号计算记录
  7. html 表格的使用
  8. 分布式锁工具之Redisson
  9. 11、Redis实现关注、取消关注以及关注和粉丝列表
  10. 分库分表 or NewSQL数据库?终于看懂应该怎么选!【转】