首页 > 编程语言 > 详细

记录一下自己搭建springboot+mybatis+druid 多数据源的过程

时间:2019-11-20 12:47:20      阅读:168      评论:0      收藏:0      [点我收藏+]

                                                                                 前言 
上次的一个项目(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 多数据源的过程

原文:https://www.cnblogs.com/xiaoyangxiaoen/p/11896560.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!