1 在Maven的pom.xml添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot3-starter</artifactId>
<version>4.3.1</version>
</dependency>
2 添加数据库信息
在application.xml中添加数据源
spring:
application:
name: OE-Statistic-Service
datasource:
dynamic:
primary: 'master'
datasource:
master:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://master_ip:master_port/oe_wim_service?useUnicode=true&serverTimezone=UTC&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
username: master_user
password: master_password
replica1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://replica1_ip:replica1_port/oe_wim_service?useUnicode=true&serverTimezone=UTC&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
username: replica1_user
password: replica1_password
replica2:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://replica2_ip:replica2_port/oe_wim_service?useUnicode=true&serverTimezone=UTC&characterEncoding=utf-8&useSSL=false&allowPublicKeyRetrieval=true
username: replica2_user
password: replica2_password
strict: false
3 在service, serviceImpl 类,或方法上添加DS注解
比如在实现类上添加
@Service
@DS("replica1")
class WimDeviceItemServiceImpl : ServiceImpl<WimDeviceItemMapper?, WimDeviceItem?>(), WimDeviceItemService