pom文件添加依赖:
<!-- Dynamic DataSource -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
.yml配置文件:
datasource:
dynamic:
primary: master
datasource:
master:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://${MYSQL_HOST:localhost1}:${MYSQL_PORT:3306}/${MYSQL_DATABASE:lease}?useUnicode=true&characterEncoding=UTF-8&serverTimezone=CTT&useSSL=false
username: ${MYSQL_USERNAME:root}
password: ${MYSQL_PASSWORD:password}
slave:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://${MYSQL_HOST:localhost2}:${MYSQL_PORT:3306}/${MYSQL_DATABASE:lease}?useUnicode=true&characterEncoding=UTF-8&serverTimezone=CTT&useSSL=false
username: ${MYSQL_USERNAME:root}
password: ${MYSQL_PASSWORD:password}
在serviceImpl中添加@DC(“value”)注解用来区分主从数据库