业务系统复杂程度增加,为了解决数据库I/O瓶颈,很自然会进行拆库拆表分服务来应对。这就会出现一个系统中可能会访问多处数据库,需要配置多个数据源。

第一种场景:项目服务从其它多处数据库取基础数据进行业务处理,因此各库之间不会出现重表等情况。

第二种场景:为了减轻写入压力进行读写分库,读走从库,写为主库。此种表名等信息皆为一致。

第三种场景:以上两种皆有。对于某些业务需要大数据量的汇总统计,希望不影响正常业务必须走从库(表信息一致),某些配置信息不存在读写压力,出现不分库(表信息不一致)

项目源代码:

https://github.com/zzsong/springboot-multiple-datasource.git

有三个目录:

one:
直接使用多@Bean配置,@MapperScan来路径区分读何库 two:
使用注解的方式来标识走何dataSource,AOP拦截注入动态数据源 third:
使用spring的Bean命名策略进行区分数据来源

项目技术选型: springBoot2.2.5 + mybatis + druid + mysql

先看主要的pom包

        <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/>
</parent> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>

application.yml

spring:
datasource:
druid:
core:
url: jdbc:mysql:///kc_core?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
schedule:
url: jdbc:mysql:///kc_schedule?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource

mysql新版本必须带有serverTimezone,不然会报连接异常。

第一种:通过@MapperScans 扫描匹配相关的数据源

@Configuration
@MapperScans({
@MapperScan(basePackages = "com.zss.one.mapper.core", sqlSessionTemplateRef = "coreSqlSessionTemplate",sqlSessionFactoryRef = "coreSqlSessionFactory"),
@MapperScan(basePackages = "com.zss.one.mapper.schedule", sqlSessionTemplateRef = "scheduleSqlSessionTemplate",sqlSessionFactoryRef = "scheduleSqlSessionFactory")
})
public class MybatisOneConfig { @Bean
@ConfigurationProperties(prefix = "spring.datasource.druid.core")
public DataSource coreDataSource(){
return DruidDataSourceBuilder.create().build();
} @Bean
public SqlSessionFactory coreSqlSessionFactory(@Qualifier("coreDataSource") DataSource coreDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(coreDataSource);
sessionFactory.getObject().getConfiguration().setJdbcTypeForNull(null);
sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return sessionFactory.getObject();
} @Bean
public SqlSessionTemplate coreSqlSessionTemplate(@Qualifier("coreSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} //======schedule========
@Bean
@ConfigurationProperties(prefix = "spring.datasource.druid.schedule")
public DataSource scheduleDataSource(){
return DruidDataSourceBuilder.create().build();
} @Bean
public SqlSessionFactory scheduleSqlSessionFactory(@Qualifier("scheduleDataSource") DataSource coreDataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(coreDataSource);
sessionFactory.getObject().getConfiguration().setJdbcTypeForNull(null);
sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return sessionFactory.getObject();
} @Bean
public SqlSessionTemplate scheduleSqlSessionTemplate(@Qualifier("scheduleSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}
}

第二种是动态数据源模式,通过AOP切入注解引导使用何数据源。用自定义注解@interface来标识方法走对应的数据源。

注意事项:类中的方法再调用带数据源的方法,不能被AOP切入
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TargetDataSource {
String value();
}

extends spring的动态DataSource路由来匹配

public class DynamicDataSource extends AbstractRoutingDataSource {

    @Override
protected Object determineCurrentLookupKey() {
return DataSourceContextRouting.getDataSourceName();
}
}
@Configuration
//@EnableConfigurationProperties(MybatisProperties.class)//不要使用此公共配置,Configuration会破坏相关dataSource的配置
@MapperScan("com.zss.two.mapper")
public class MybatisConfig { @Bean
@ConfigurationProperties(prefix = "spring.datasource.druid.core")
public DataSource coreDataSource() {
return DruidDataSourceBuilder.create().build();
} @Bean
@ConfigurationProperties(prefix = "spring.datasource.druid.schedule")
public DataSource scheduleDataSource() {
return DruidDataSourceBuilder.create().build();
} @Autowired
@Qualifier("coreDataSource")
private DataSource coreDataSource; @Autowired
@Qualifier("scheduleDataSource")
private DataSource scheduleDataSource; @Bean
public DynamicDataSource dataSource() {
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DataSourceConstants.CORE_DATA_SOURCE, coreDataSource);
targetDataSources.put(DataSourceConstants.SCHEDULE_DATA_SOURCE, scheduleDataSource); DynamicDataSource dataSource = new DynamicDataSource(); //设置数据源映射
dataSource.setTargetDataSources(targetDataSources);
//// 设置默认数据源,当无法映射到数据源时会使用默认数据源
dataSource.setDefaultTargetDataSource(coreDataSource);
dataSource.afterPropertiesSet();
return dataSource;
}
/**
* 根据数据源创建SqlSessionFactory
*/
@Bean
public SqlSessionFactory sqlSessionFactory(DynamicDataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.getObject().getConfiguration().setJdbcTypeForNull(null);
sessionFactory.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return sessionFactory.getObject();
} @Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
}

第三种,自定义Bean命名策略,按beanName进行自动匹配使用数据源

@Component
public class CoreBeanNameGenerator implements BeanNameGenerator {
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
return "core"+ ClassUtils.getShortName(definition.getBeanClassName());
}
} @Component
public class ScheduleBeanNameGenerator implements BeanNameGenerator {
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
return "schedule"+ ClassUtils.getShortName(definition.getBeanClassName());
}
}

使用mybatis MapperScannerConfigurer自动扫描,将Mapper接口生成注入到spring

    @Bean
public MapperScannerConfigurer coreMapperScannerConfig(CoreBeanNameGenerator coreBeanNameGenerator){
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setNameGenerator(coreBeanNameGenerator);
configurer.setBasePackage("com.zss.third.mapper.core,com.zss.third.mapper.order");
configurer.setSqlSessionFactoryBeanName("coreSqlSessionFactory");
configurer.setSqlSessionTemplateBeanName("coreSqlSessionTemplate");
return configurer;
} @Bean
public MapperScannerConfigurer scheduleMapperScannerConfig(ScheduleBeanNameGenerator scheduleBeanNameGenerator){
MapperScannerConfigurer configurer = new MapperScannerConfigurer();
configurer.setNameGenerator(scheduleBeanNameGenerator);
configurer.setBasePackage("com.zss.third.mapper.schedule,com.zss.third.mapper.order");
configurer.setSqlSessionFactoryBeanName("scheduleSqlSessionFactory");
configurer.setSqlSessionTemplateBeanName("scheduleSqlSessionTemplate");
return configurer;
}

到此,三种多数据源匹配主要点介绍完,详细直接下载github项目。 在resources/db含有相关测试表及数据脚本。

springboot2 + mybatis 多种方式实现多数据配置的更多相关文章

  1. Spring实现Ioc的多种方式--控制反转、依赖注入、xml配置的方式实现IoC、对象作用域

    Spring实现Ioc的多种方式 一.IoC基础 1.1.概念: 1.IoC 控制反转(Inversion of Control) IoC是一种设计思想. 2.DI 依赖注入 依赖注入是实现IoC的一 ...

  2. Django 缓存配置的多种方式

    django 的缓存配置有多种方式,主要包含以下几种: 1.开发调试模式 2.内存模式 3.使用文件 4.直接使用数据库 5.使用redis或者memcache 这里主要是记录一下那些不常用,但是在微 ...

  3. Spring Boot 入门系列(二十三)整合Mybatis,实现多数据源配置!

    d之前介绍了Spring Boot 整合mybatis 使用注解方式配置的方式实现增删改查以及一些复杂自定义的sql 语句 .想必大家对spring boot 项目中,如何使用mybatis 有了一定 ...

  4. idea打包jar的多种方式

    这里总结出用IDEA打包jar包的多种方式,以后的项目打包Jar包可以参考如下形式: 用IDEA自带的打包形式 用Maven插件maven-shade-plugin打包 用Maven插件maven-a ...

  5. MySQL JDBC/MyBatis Stream方式读取SELECT超大结果集

    情景: 遍历并处理一个大表中的所有数据, 这个表中的数据可能会是千万条或者上亿条, 很多人可能会说用分页limit……但需求本身一次性遍历更加方便, 且Oracle/DB2都有方便的游标机制. 对DB ...

  6. Spring学习总结(一)——Spring实现IoC的多种方式

    控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法.没有IoC的程序中我们使用面向对象编程对象的创 ...

  7. java 获取classpath下文件多种方式

    java 获取classpath下文件多种方式 一:properties下配置 在resources下定义server.properties register.jks.path=classpath\: ...

  8. myBatis 基础测试 表关联关系配置 集合 测试

    myBatis 基础测试 表关联关系配置 集合 测试 测试myelipse项目源码 sql 下载 http://download.csdn.net/detail/liangrui1988/599388 ...

  9. Spring实现IoC的多种方式

    目录 一.使用XML配置的方式实现IOC 二.使用Spring注解配置IOC 三.自动装配 四.零配置实现IOC 五.示例下载 控制反转IoC(Inversion of Control),是一种设计思 ...

随机推荐

  1. mongodb写入安全级别

    MongoDB的写安全机制 写入安全(Write Concern)是一种由客户端设置的,用于控制写入安全级别的机制,通过使用写入安全机制可以提高数据的可靠性. MongoDB提供四种写入级别,分别是: ...

  2. Presto单机/集群模式安装笔记

    Presto单机/集群模式安装笔记 一.安装环境 二.安装步骤 三.集群模式安装: 3.1 集群模式修改配置部分 3.1.1 coordinator 节点配置. Node172配置 3.1.2 nod ...

  3. Spring Security基于Oauth2的SSO单点登录怎样做?一个注解搞定

    一.说明 单点登录顾名思义就是在多个应用系统中,只需要登录一次,就可以访问其他相互信任的应用系统,免除多次登录的烦恼.本文主要介绍 同域 和 跨域 两种不同场景单点登录的实现原理,并使用 Spring ...

  4. Eureka 注册中心看这一篇就够了

    服务注册中心是服务实现服务化管理的核心组件,类似于目录服务的作用,主要用来存储服务信息,譬如提供者 url 串.路由信息等.服务注册中心是微服务架构中最基础的设施之一. 在微服务架构流行之前,注册中心 ...

  5. 前端每日实战:39# 视频演示如何用纯 CSS 创作一个表达怀念童年心情的条纹彩虹心特效

    效果预览 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/QxbmxJ 可交互视频教程 此视频 ...

  6. 大厂常问iOS面试题--性能优化篇

    1.造成tableView卡顿的原因有哪些? 1.最常用的就是cell的重用, 注册重用标识符 如果不重用cell时,每当一个cell显示到屏幕上时,就会重新创建一个新的cell 如果有很多数据的时候 ...

  7. 【MySQL 原理分析】之 Explain & Trace 深入分析全模糊查询走索引的原理

    一.背景 今天,交流群有一位同学提出了一个问题.看下图: 之后,这位同学确实也发了一个全模糊查询走索引的例子: 到这我们可以发现,这两个sql最大的区别是:一个是查询全字段(select *),而一个 ...

  8. 数据结构 4 时间复杂度、B-树 B+树 具体应用与理解

    前言 面试中,经常会问到有关于MYSQL 索引的相关概念,我们之前也都学过有关树的概念.以及二叉树.二叉查找树.红黑树等.这一节,来关注经常是数据库索引中使用的B-树 在说这些之前,我们需要了解时间复 ...

  9. 阿里云Tomcat配置

    阿里云Tomcat配置并开放 本文可对以下问题提供参考 服务器 如何配置 Tomcat 配置 端口在监听,但是外网无法访问怎么办 注意事项: 对于阿里云服务器相对较为特殊,因为阿里云服务器除了需要在系 ...

  10. 「从零单排HBase 05」核心特性region split

    HBase拥有出色的扩展性,其中最依赖的就是region的自动split机制. 1.split触发时机与策略 前面我们已经知道了,数据写入过程中,需要先写memstore,然后memstore满了以后 ...