MybatisPlus——實現多數據源操作

多數據源

適用:一般工作時候會有多個資料庫,每個庫對應不同的業務數據。程式如果每次數據都訪問同一個資料庫,該資料庫壓力很大訪問會很慢。

官方文檔://baomidou.com/(建議多看看官方文檔,每種功能裡面都有講解)【本文章使用的mybatisplus版本為3.5.2】

約定

  1. 本框架只做 切換數據源 這件核心的事情,並不限制你的具體操作,切換了數據源可以做任何CRUD。
  2. 配置文件所有以下劃線 _ 分割的數據源 首部 即為組的名稱,相同組名稱的數據源會放在一個組下。
  3. 切換數據源可以是組名,也可以是具體數據源名稱。組名則切換時採用負載均衡演算法切換。
  4. 默認的數據源名稱為 master ,你可以通過 spring.datasource.dynamic.primary 修改。
  5. 方法上的註解優先於類上註解。
  6. DS支援繼承抽象類上的DS,暫不支援繼承介面上的DS。

使用

1、導入依賴

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    <version>3.5.1</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>

2、yaml 配置不同的數據源

spring:
  datasource:
    dynamic:
      primary: master #設置默認的數據源或者數據源組,默認值即為master
      strict: false #嚴格匹配數據源,默認false. true未匹配到指定數據源時拋異常,false使用默認數據源
      datasource:
        master:
          url: jdbc:mysql://xx.xx.xx.xx:3306/dynamic
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver # 3.2.0開始支援SPI可省略此配置
        slave_1:
          url: jdbc:mysql://xx.xx.xx.xx:3307/dynamic
          username: root
          password: 123456
          driver-class-name: com.mysql.jdbc.Driver
        slave_2:
          url: ENC(xxxxx) # 內置加密,使用請查看詳細文檔
          username: ENC(xxxxx)
          password: ENC(xxxxx)
          driver-class-name: com.mysql.jdbc.Driver
       #......省略
       #以上會配置一個默認庫master,一個組slave下有兩個子庫slave_1,slave_2

註:多數據源配置規範

# 多主多從                      純粹多庫(記得設置primary)                   混合配置
spring:                               spring:                               spring:
  datasource:                           datasource:                           datasource:
    dynamic:                              dynamic:                              dynamic:
      datasource:                           datasource:                           datasource:
        master_1:                             mysql:                                master:
        master_2:                             oracle:                               slave_1:
        slave_1:                              sqlserver:                            slave_2:
        slave_2:                              postgresql:                           oracle_1:
        slave_3:                              h2:                                   oracle_2:

3、使用 @DS 切換數據源。

@DS 可以註解在方法上或類上,同時存在就近原則 方法上註解 優先於 類上註解

@Service
@DS("slave")
public class UserServiceImpl implements UserService {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public List selectAll() {
    return  jdbcTemplate.queryForList("select * from user");
  }
  
  @Override
  @DS("slave_1")
  public List selectByCondition() {
    return  jdbcTemplate.queryForList("select * from user where age >10");
  }
}