记录一下自己搭建springboot+mybatis+druid 多数据源的过程
前言
上次的一个项目(springboot+mybatis+vue),做到后面的时间发现需要用到多数据源。当时没有思路。。后来直接用了jdbc来实现。
这几天不是很忙,所以决定自己再搭建一次。不多说,开干。
首先。idea快速生成一个springboot项目。这个步骤就不贴出来了。以下是项目结构。
1. pom.xml需要 加入以下依赖包
<!-- druid -->
<!--阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.14</version>
</dependency> <!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency> <!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency> <!-- lombok 插件-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
2. application.yml 的配置
#durid数据库连接池设置
spring:
aop:
proxy-target-class: true
# 数据源 1
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123
# 数据源 2
datasource2:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/uat_data?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123 # 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 15
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,log4j2
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
druid:
remove-abandoned: true
remove-abandoned-timeout: 180
log-abandoned: true # 这里不加这个,会导致项目扫描不到mapper.xml 报找不到方法错误
mybatis:
mapper-locations: classpath:primary/mapper/*.xml,classpath:second/mapper/*.xml 3.创建 controller 层, service层,mapper层(这里区分开成两个mapper 一个是数据源1的 一个是数据源2的),resource 下面也区分对应的mapper,
然后自己写一个简单的controller调用,我自己写的也是简单的查询。controller-service-dao

4.数据源1 的配置
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 org.mybatis.spring.annotation.MapperScan; import javax.sql.DataSource; //表示这个类为一个配置类
@Configuration
// 配置mybatis的接口类放的地方
@MapperScan(basePackages = "com.example.duoshuyuan_demo.primary" , sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSource { // 将这个对象放入Spring容器中
@Bean(name = "DataSource_primary")
// 表示这个数据源是默认数据源
@Primary
// 读取application.yml中的配置参数映射成为一个对象
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource(){
System.out.println("数据源1启动成功===========================");
return DataSourceBuilder.create().build();
} // 将这个对象放入Spring容器中
@Bean(name = "primarySqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("DataSource_primary") DataSource dataSource) throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// 设置mybatis的xml所在位置
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:primary/mapper/*.xml"));
return bean.getObject();
} /**
* 这里应该配置的是 该数据源的事务
* */
@Bean(name = "primaryTransactionManager")
@Primary
public DataSourceTransactionManager primaryTransactionManager(@Qualifier("DataSource_primary") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "primarySqlSessionTemplate")
@Primary
public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
} 5.数据源2 的配置
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.mybatis.spring.annotation.MapperScan; import javax.sql.DataSource; @Configuration
@MapperScan(basePackages = "com.example.duoshuyuan_demo.second" , sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSource { @Bean(name = "DataSource_second")
@ConfigurationProperties(prefix = "spring.datasource2")
public DataSource secondDataSource(){
System.out.println("数据源2启动成功***********************");
return DataSourceBuilder.create().build();
} @Bean(name = "secondSqlSessionFactory")
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("DataSource_second") DataSource dataSource) throws Exception{
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:second/mapper/*.xml"));
bean.setDataSource(dataSource);
return bean.getObject();
} @Bean(name = "secondTransactionManager")
public DataSourceTransactionManager secondTransactionManager(@Qualifier("DataSource_second") DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "secondSqlSessionTemplate")
public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
return new SqlSessionTemplate(sqlSessionFactory);
}
}
6.修改启动类
@MapperScan({"com.example.duoshuyuan_demo.primary.mapper","com.example.duoshuyuan_demo.second.mapper"})
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
7.启动项目。访问controller

8.访问结果




OK。搞定。以上就是自己参考网上+自己踩坑搭建的过程。。。。。。
说下遇到的问题
1.出现xml文件 方法找不到的问题。一般加在yml文件加
mybatis:
mapper-locations: classpath:primary/mapper/*.xml,classpath:second/mapper/*.xml
2.出现 dataSource or dataSourceClassName or jdbcUrl is required,一般是 dataSource: 的 jdbc-url写成了 url
3.记得在启动类加 @MapperScan注解。
4.还有个问题就是 我在复制数据源2的配置的时候。
@ConfigurationProperties(prefix = "spring.datasource2")
prefix 里面需要对应你自己起的配置前缀名,ben加载配置。是不会去检验你的参数是否正确的,只加载值进去创建。(这里坑了我一晚上的时间)

记录一下自己搭建springboot+mybatis+druid 多数据源的过程的更多相关文章
- springboot+mybatis+druid+atomikos框架搭建及测试
前言 因为最近公司项目升级,需要将外网数据库的信息导入到内网数据库内.于是找了一些springboot多数据源的文章来看,同时也亲自动手实践.可是过程中也踩了不少的坑,主要原因是我看的文章大部分都是s ...
- springboot+mybatis+druid+sqlite/mysql/oracle
搭建springboot+mybatis+druid+sqlite/mysql/oracle附带测试 1.版本 springboot2.1.6 jdk1.8 2.最简springboot环境 http ...
- 基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建
基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建 前言 最近做回后台开发,重新抓起以前学过的SSM(Spring+Sp ...
- 3分钟搞定SpringBoot+Mybatis+druid多数据源和分布式事务
文章来自: https://blog.csdn.net/qq_29242877/article/details/79033287 在一些复杂的应用开发中,一个应用可能会涉及到连接多个数据源,所谓多数据 ...
- SpringBoot+Mybatis+ Druid+PageHelper 实现多数据源并分页
前言 本篇文章主要讲述的是SpringBoot整合Mybatis.Druid和PageHelper 并实现多数据源和分页.其中SpringBoot整合Mybatis这块,在之前的的一篇文章中已经讲述了 ...
- SpringBoot+MyBatis配置多数据源
SpringBoot 可以支持多数据源,这是一个非常值得学习的功能,但是从现在主流的微服务的架构模式中,每个应用都具有唯一且准确的功能,多数据源的需求很难用到,考虑到实际情况远远比理论复杂的多,这里还 ...
- springboot+mybatis集成多数据源MySQL/Oracle/SqlServer
日常开发中可能时常会遇到一些这样的需求,业务数据库和第三方数据库,两个或多个数据库属于不同数据库厂商,这时候就需要通过配置来实现对数据库实现多源处理.大致说一下我的业务场景,框架本身是配置的sprin ...
- 搭建Springboot+mybatis+redis+druid
2019独角兽企业重金招聘Python工程师标准>>> 准备工作 JDK:1.8 使用技术:SpringBoot.Dubbo.Mybatis.Druid 开发工具:Intelj ID ...
- SpringBoot+Mybatis+Druid批量更新 multi-statement not allow异常
本文链接:https://blog.csdn.net/weixin_43947588/article/details/90109325 注:该文是本博主记录学习之用,没有太多详细的讲解,敬请谅解! ...
随机推荐
- Beego模板 循环和判断几个例子
Beego模板 循环和判断几个例子 Beego的前端几乎是另一种语言.一些循环.判断,不细看文档真的做不出来. 0. Beego的View模板语法规则: beego前端(view)统一使用了 {{ 和 ...
- c++中sort基础用法
用法一:数组排序 对一个数组进行升序排序 #include <algorithm> #include <iostream> #include <cstdio> us ...
- 分类问题(三)混淆矩阵,Precision与Recall
混淆矩阵 衡量一个分类器性能的更好的办法是混淆矩阵.它基于的思想是:计算类别A被分类为类别B的次数.例如在查看分类器将图片5分类成图片3时,我们会看混淆矩阵的第5行以及第3列. 为了计算一个混淆矩阵, ...
- mybatis一级缓存和二级缓存(一)
一级缓存: 就是Session级别的缓存.一个Session做了一个查询操作,它会把这个操作的结果放在一级缓存中. 如果短时间内这个session(一定要同一个session)又做了同一个操作,那么h ...
- PP: A dual-stage attention-based recurrent neural network for time series prediction
Problem: time series prediction The nonlinear autoregressive exogenous model: The Nonlinear autoregr ...
- 在 window 上卸载 mysql
1.停止 mysql 服务 开始——>控制面板——>管理工具——>服务,停掉 MySQL 的服务 2.卸载安装包 控制面板-添加删除程序,找到MySQL,卸载(可能会有多个安装包,需 ...
- linux - 异常:安装包冲突 conflicts with
问题描述 解决方案 删除冲突的包 命令格式:yum -y remove 包名 yum -y remove httpd24u yum -y remove httpd24u-tools
- window.resizeTo
概述 动态调整窗口的大小. 语法 window.resizeTo(aWidth, aHeight) 参数 aWidth 是一个整数,表示新的 outerWidth(单位:像素)(包括滚动条.窗口边框等 ...
- 【做题笔记】洛谷P1506 拯救oibh总部
跑一遍染色法,最后判断哪些位置没被染色即可 一些技巧: 为了判断方便,把字符转换成 int 型的数字. 注意边界问题 详细解释见代码 #include <iostream> #includ ...
- Windows ThinPC 7 部署后续设置与本地化
还原注销背景 %system32%\oobe\info\backgrounds 删除该目录下所有文件后变为wes7背景 24时制与非UNICODE字符乱码解决 Control Panel \ Regi ...
7.启动项目。访问controller