1.Maven 包
com.baomidou
dynamic-datasource-spring-boot-starter
3.1.1
2.配置文件
###MySQL druid多数据源配置(纯粹多库)###
#去除durid配置
spring.autoconfigure.exclude=com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
#指定默认数据源(必须配置)
spring.datasource.dynamic.primary=db01
#设置严格模式,默认false不启动. 启动后在未匹配到指定数据源时候回抛出异常,不启动会使用默认数据源.
spring.datasource.dynamic.strict=false
#db01库
spring.datasource.dynamic.datasource.db01.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.db01.url=jdbc:mysql://X.X.X.X:3306/DB-Name?serverTimezone=GMT&useSSL=false
spring.datasource.dynamic.datasource.db01.username=XXX
spring.datasource.dynamic.datasource.db01.password=XXXX
#db02库
spring.datasource.dynamic.datasource.db02.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.dynamic.datasource.db02.url=jdbc:mysql://X.X.X.X:3306/DB-Name?serverTimezone=GMT&useSSL=false
spring.datasource.dynamic.datasource.db02.username=XXX
spring.datasource.dynamic.datasource.db02.password=XXXX
#数据源基础配置
spring.datasource.dynamic.druid.initial-size=5
spring.datasource.dynamic.druid.min-idle=5
spring.datasource.dynamic.druid.max-active=20
# 配置获取连接等待超时的时间
spring.datasource.dynamic.druid.max-wait=6000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.dynamic.druid.time-between-eviction-runs-millis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.dynamic.druid.min-evictable-idle-time-millis=300000
spring.datasource.dynamic.druid.validation-query=SELECT 1 FROM DUAL
spring.datasource.dynamic.druid.test-while-idle=true
spring.datasource.dynamic.druid.test-on-borrow=false
spring.datasource.dynamic.druid.test-on-return=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.dynamic.druid.pool-prepared-statements=true
spring.datasource.dynamic.druid.max-pool-prepared-statement-per-connection-size=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.dynamic.druid.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.dynamic.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
3.示例代码
@Mapper
@DS("db01")
public interface InfoDao {
@Select("SELECT name,address FROM table_name WHERE id = #{id}")
> getInfos(@Param("id") int id);
}
==============================================
@Mapper
@DS("db02")
public interface UserDao {
@Select("SELECT xx,xx,xx FROM table_name WHERE id = #{id}")
> getUser(@Param("id") int id);
}