记录一下自己搭建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 注:该文是本博主记录学习之用,没有太多详细的讲解,敬请谅解! ...
随机推荐
- js对象赋值
看到一道题: 根据包名,在指定空间中创建对象 效果 namespace({a: {test: 1, b: 2}}, 'a.b.c.d') 结果 {a: {test: 1, b: {c: {d: {}} ...
- C#继承是个啥
继承: 字面意思就是继承 如地主老王有500亩地,老王的儿子小王可以种这五百亩地可以随便拿这五百亩地上面的任何东西 如Controller 你要用从一个controller调用另一个controlle ...
- 机器学习作业(六)支持向量机——Matlab实现
题目下载[传送门] 第1题 简述:支持向量机的实现 (1)线性的情况: 第1步:读取数据文件,可视化数据: % Load from ex6data1: % You will have X, y in ...
- Windows中配置MySQL环境变量
安装好MySQL后,在Windows环境下配置环境变量 1)新建MYSQL_HOME系统变量 配置MySQL的安装路径:C:\Program Files\MySQL\MySQL Server 5.7 ...
- SpringBoot整合RabbitMQ出现org.springframework.amqp.AmqpException: No method found for class
@Component @RabbitListener(queues="my_fanout") public class Consumer { @RabbitHandler ...
- 开班信息CSS实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Cleaning Data in R
目录 R 中清洗数据 常见三种查看数据的函数 Exploring raw data 使用dplyr包里面的glimpse函数查看数据结构 \(提取指定元素 ```{r} # Histogram of ...
- C++-POJ2960-S-Nim-[限制型Nim]
每次只能从取集合S中个数的物品,其他和普通Nim游戏相同 预处理出每种物品堆的sg值,然后直接xor一下,xor-sum>0即必胜 #include <set> #include & ...
- 《TCP/IP入门经典》摘录--Part 1
TCP/IP基础知识 什么是TCP/IP Transmission Control Protocol/Internet Protocol的简写,中译名为传输控制协议/因特网互联协议,又名网络通讯协议, ...
- wcf接口输出为json格式
接口定义: [OperationContract] [WebInvoke(UriTemplate = "AddTask?taskId={taskId}&processGuid={pr ...