引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
配置文件
spring:
datasource:
dynamic:
primary: master # 配置默认数据库
datasource:
master:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost1:3306/datasource1?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: ENC(MR9DBOU3bqxDAgVTdv5pAIzkpZ0jHKi6)
slave:
enabled: true
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost2:3306/datasource2?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: ENC(MR9DBOU3bqxDAgVTdv5pAIzkpZ0jHKi6)
druid:
initialSize: 5
minIdle: 10
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
maxEvictableIdleTimeMillis: 900000
validationQuery: SELECT 1
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
使用@DS注解切换数据源