spring boot動態切換數據源的實現

當數據量比較大的時候,我們就需要考慮讀寫分離瞭,也就是動態切換數據庫連接,對指定的數據庫進行操作。在spring中實現動態的切換無非就是利用AOP實現。我們可以使用mybatis-plus作者開發的插件dynamic-datasource-spring-boot-starter。

demo地址:https://github.com/songshijun1995/spring-boot-dynamic-demo

新建項目引入依賴

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

配置yml

server:
 port: 8081
 servlet:
  context-path: /

spring:
 application:
  name: spring-boot-dynamic-demo
 datasource:
  dynamic:
   primary: master #設置默認的數據源或者數據源組,默認值即為master
   strict: false #設置嚴格模式,默認false不啟動. 啟動後在未匹配到指定數據源時候會拋出異常,不啟動則使用默認數據源.
   datasource:
    master: #替換成自己的數據庫連接
     url: jdbc:mysql://127.0.0.1:3306/dynamic1?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowMultiQueries=true&rewriteBatchedStatements=true
     username: root
     password: 123456
     driver-class-name: com.mysql.cj.jdbc.Driver
    slave_1:
     url: jdbc:mysql://127.0.0.1:3306/dynamic2?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowMultiQueries=true&rewriteBatchedStatements=true
     username: root
     password: 123456
     driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
 configuration:
  log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
 global-config:
  db-config:
   logic-delete-value: 1
   logic-not-delete-value: 0
   logic-delete-field: deleted
 mapper-locations: classpath:/mapper/**.xml

logging:
 level:
  ROOT: INFO
  com.dynamic.dynamicdemo: DEBUG
 pattern:
  file: '%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{50} - %msg%n'
 file:
  name: ${logging.file.path}/${spring.application.name}.log
  path: /home/logs/${spring.application.name}
 logback:
  rollingpolicy:
   max-file-size: 10MB
   max-history: 30

mybatis-plus和swagger配置我就不多說瞭,demo裡都有

如何使用

package com.dynamic.dynamicdemo.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dynamic.dynamicdemo.dto.PageRequest;
import com.dynamic.dynamicdemo.dto.UserInfoRequest;
import com.dynamic.dynamicdemo.entities.BaseEntity;
import com.dynamic.dynamicdemo.entities.UserInfo;
import com.dynamic.dynamicdemo.mapper.UserInfoMapper;
import com.dynamic.dynamicdemo.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

  @DS("master")
  @Transactional(rollbackFor = Exception.class)
  @Override
  public String saveUser(UserInfoRequest request) {
    UserInfo userInfo = new UserInfo();
    BeanUtils.copyProperties(request, userInfo);
    boolean save = save(userInfo);
    if (!save) {
      throw new RuntimeException("添加用戶失敗");
    }
    return "添加用戶成功";
  }

  @DS("slave_1")
  @Override
  public IPage<UserInfo> pageUser(PageRequest request) {
    return page(new Page<>(request.getPageNum(), request.getPageSize()), Wrappers.<UserInfo>lambdaQuery().orderByDesc(BaseEntity::getCreateTime));
  }
}

在方法上或者類上加@DS(“master”)註解,來指定數據源

更換為自己的數據庫連接,以及建庫,運行resources/sql目錄下的sql文件
然後啟動項目訪問http://127.0.0.1:8081/doc.html進行測試

到此這篇關於spring boot動態切換數據源的實現的文章就介紹到這瞭,更多相關spring boot動態切換數據源內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: