多数据源的实现方式大致分为注解和分包两种方式,因不希望在每个service都要加注解,故我的项目中选择的是基于分包的方式。
SpringBoot 版本为v2.1.3.RELEASE,Mybatis plus 版本为3.3.2。
- 配置文件application.yml
server:
port: 9003
spring:
application:
name: xxx
datasource:
druid:
test1:
url: jdbc:mysql://localhost:3306/quartz?characterEncoding=utf-8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource # 下面为连接池的补充设置,应用到上面所有数据源中
initialSize: 5 # 初始化大小,最小,最大
maxActive: 20
minIdle: 5
maxWait: 60000 # 配置获取连接等待超时的时间
timeBetweenEvictionRunsMillis: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
minEvictableIdleTimeMillis: 30000 # 配置一个连接在池中最小生存的时间,单位是毫秒
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
test2:
url: jdbc:mysql://192.168.101.129:3306/db2?characterEncoding=utf-8&useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
initialSize: 5 #初始建立连接数量
minIdle: 5 #最小连接数量
maxActive: 20 #最大连接数量
maxWait: 10000 #获取连接最大等待时间,毫秒
testOnBorrow: true #申请连接时检测连接是否有效
testOnReturn: false #归还连接时检测连接是否有效
timeBetweenEvictionRunsMillis: 60000 #配置间隔检测连接是否有效的时间(单位是毫秒)
minEvictableIdleTimeMillis: 300000 #连接在连接池的最小生存时间(毫秒)
- 数据源配置
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.core