spring boot+mybatis-plus配置读写分离

对于mysql主从机制的读写分离,对于写操作写入主库,读取操作读取从库

一、安装依赖

复制代码
<dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
            <version>3.3.6</version>
        </dependency>

二、配置文件配置数据源

复制代码
spring:
  datasource:
    dynamic:
      #默认数据源
      primary: master
      datasource:
        master:
          username: root
          password: xxxxx
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/xx?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
        slave:
          username: root
          password: xxx
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/xx?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8

三、在service,如果是读取操作的话,则需要加上注解@DS("slave")即可,可看如下示例

复制代码
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {

    //读取走从库
    @Override
    @DS("slave")
    public List<TUser> getUserList(){
        return baseMapper.selectList(null);
    }

    //写操作默认走主库
    @Override
    @Transactional
    public String adUser(TUser user){
        baseMapper.insert(user);
        return "OK";
    }
}
相关推荐
架构师沉默20 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
RoyLin20 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在20 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
Moonbit20 小时前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言
Goland猫21 小时前
电商架构图
后端
Java中文社群21 小时前
重要:Java25正式发布(长期支持版)!
java·后端·面试
我是天龙_绍21 小时前
Whisper 通过 mp3输出中文
后端
zjjuejin21 小时前
Maven环境搭建
后端·maven
我是天龙_绍21 小时前
项目根目录有requirements.txt 如何安装
后端
bobz96521 小时前
MPLS VPN | SRV6 TE 安全隔离路由技术
后端