热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

springboot在mybatisplus中使用多数据源

链接:MyBatis-Plus推荐的多数据源.链接:一个基于s

链接: MyBatis-Plus推荐的多数据源.

链接: 一个基于springboot的快速集成多数据源的启动器.

链接: 多数据源.

链接: 多数据源.

链接: dynamic-datasource文档.

dynamic-datasource-spring-boot-starter

是一个基于springboot的快速集成多数据源的启动器,主要用于读写分离,一主多从的环境,纯多库都行

如果你的项目比较复杂,建议使用 sharding-jdbc

导入依赖

<dependency>
<groupId>com.baomidougroupId>
<artifactId>dynamic-datasource-spring-boot-starterartifactId>
<version>${version}version>
dependency>

配置yml

spring:
datasource:
druid:
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
filter:
stat:
merge-sql: true
slow-sql-millis: 5000
#合并多个DruidDataSource的监控数据
use-global-data-source-stat: true
#设置访问druid监控页的账号和密码,默认没有
stat-view-servlet:
login-username:
login-password:
enabled: true
dynamic:
primary: master #设置默认的数据源或者数据源组,默认值即为master
strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
datasource:
master:
url:
username: xxx
password: xxx
driver-class-name: oracle.jdbc.OracleDriver
druid:
#初始化时建立物理连接的个数
initial-size: 5
#最小连接池数量
min-idle: 5
#最大连接池数量
max-active: 20
#获取连接时最大等待时间,单位毫秒
max-wait: 60000
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
test-while-idle: true
#既作为检测的间隔时间又作为testWhileIdel执行的依据
time-between-eviction-runs-millis: 60000
#销毁线程时检测当前连接的最后活动时间和当前时间差大于该值时,关闭当前连接
min-evictable-idle-time-millis: 30000
#用来检测连接是否有效的sql 必须是一个查询语句
validation-query: select 1 from dual
#申请连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
test-on-borrow: false
#归还连接时会执行validationQuery检测连接是否有效,开启会降低性能,默认为true
test-on-return: false
#是否缓存preparedStatement,mysql5.5+建议开启
pool-prepared-statements: true
#当值大于0时poolPreparedStatements会自动修改为true
max-pool-prepared-statement-per-connection-size: 20
slave_1:
url:
username: xxx
password: xxx
driver-class-name: oracle.jdbc.OracleDriver
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
test-while-idle: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 30000
test-on-borrow: false
test-on-return: false
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20

引入druid的注意

排除 原生Druid的快速配置类

@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

为什么要排除DruidDataSourceAutoConfigure

DruidDataSourceAutoConfigure会注入一个DataSourceWrapper,其会在原生的spring.datasource下找url,username,password等。而我们动态数据源的配置路径是变化的。

使用 @DS 切换数据源

@DS 可以注解在方法上和类上,同时存在方法注解优先于类上注解,强烈建议注解在mapper接口方法上。

@DS("master")
public interface UserMapper {
@Select("SELECT * FROM user")
@DS
List<User> selectAll();
}

推荐阅读
author-avatar
kas8288408
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有