java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Boot MyBatis自动主从切换

Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能

作者:山高自有客行路

这篇文章主要介绍了Spring Boot项目中结合MyBatis实现MySQL的自动主从切换功能,本文分步骤给大家介绍的非常详细,感兴趣的朋友一起看看吧

原理解析

1. MySQL主从复制(Master-Slave Replication)

2. 读写分离

3. 自动故障转移

实现步骤详解

1. 引入依赖

pom.xml中添加必要的依赖,包括Spring Boot Starter、MyBatis Starter以及ShardingSphere:

深色版本

<dependencies>
    <!-- Spring Boot Starter -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!-- MyBatis Starter -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    <!-- ShardingSphere for read-write splitting -->
    <dependency>
        <groupId>org.apache.shardingsphere</groupId>
        <artifactId>sharding-jdbc-spring-boot-starter</artifactId>
        <version>4.1.1</version>
    </dependency>
</dependencies>

2. 配置数据源

编辑application.yml文件以配置多个数据源,并设置ShardingSphere规则以实现读写分离:

深色版本

spring:
  shardingsphere:
    datasource:
      names: master,slave0,slave1
      master:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://master_host:3306/your_db?useSSL=false&serverTimezone=UTC
        username: your_username
        password: your_password
      slave0:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://slave0_host:3306/your_db?useSSL=false&serverTimezone=UTC
        username: your_username
        password: your_password
      slave1:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://slave1_host:3306/your_db?useSSL=false&serverTimezone=UTC
        username: your_username
        password: your_password
    masterslave:
      load-balance-algorithm-type: round_robin # 负载均衡策略
      name: ms_ds # 数据源名称
      master-data-source-name: master # 主库数据源名称
      slave-data-source-names: slave0,slave1 # 从库数据源名称列表
    props:
      sql:
        show: true # 是否显示SQL语句

3. 配置MyBatis

创建MyBatis Mapper接口,并使用注解或XML配置SQL语句。这里以注解方式为例:

深色版本

package com.example.demo.mapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
@Mapper
public interface UserMapper {
    /**
     * 查询所有用户信息.
     * 注意:对于查询操作,ShardingSphere会选择其中一个从库来执行查询。
     *
     * @return 用户信息列表
     */
    @Select("SELECT * FROM users")
    List<Map<String, Object>> findAllUsers();
    /**
     * 更新用户信息.
     * 注意:写操作只会针对主库执行。
     *
     * @param id 用户ID
     * @param newName 新用户名
     */
    void updateUserById(@Param("id") Long id, @Param("newName") String newName);
}

确保你的Spring Boot应用扫描到Mapper接口。可以在主类上添加@MapperScan注解:

深色版本

package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

4. 使用Mapper进行数据库操作

现在你可以在Service层中注入并使用Mapper接口来进行数据库操作:

深色版本

package com.example.demo.service;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;
    /**
     * 获取所有用户信息.
     *
     * @return 用户信息列表
     */
    public List<Map<String, Object>> getAllUsers() {
        return userMapper.findAllUsers();
    }
    /**
     * 更新用户名称.
     *
     * @param id       用户ID
     * @param newName 新用户名
     */
    public void updateUserName(Long id, String newName) {
        userMapper.updateUserById(id, newName);
    }
}

注意事项及最佳实践

到此这篇关于Spring Boot项目中结合MyBatis实现MySQL的自动主从切换的文章就介绍到这了,更多相关Spring Boot MyBatis自动主从切换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文