springBoot 多資料來源配置

好mingzi给猪了發表於2024-04-18

常規資料來源

# 應用埠
server:
  port: 5555
spring:
  datasource:
    username: root
    password: ffjy1101
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
  application:

多資料來源:
1.修改yml

# 應用埠
server:
  port: 5555
spring:
  datasource:
    dynamic:
      primary: test1 #預設使用test1資料來源
      strict: false
      datasource:
        test1:
          username: root
          password: ffjy1101
          url: jdbc:mysql://localhost:3306/test1?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
          driver-class-name: com.mysql.cj.jdbc.Driver
        test2:
          username: root
          password: ffjy1101
          url: jdbc:mysql://localhost:3306/test2?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=false
          driver-class-name: com.mysql.cj.jdbc.Driver


2.新增pom.xml

<dependency>
           <groupId>com.baomidou</groupId>
           <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
           <version>3.5.0</version>
        </dependency> 

3.配置

//預設使用test1資料來源,使用其他資料來源需在類或方法上新增註解
@DS("test2")

相關文章