Spring Boot項目中結合MyBatis實現(xiàn)MySQL的自動主從切換功能
原理解析
1. MySQL主從復制(Master-Slave Replication)
- 工作原理:MySQL主從復制通過二進制日志(binary log)來同步數(shù)據(jù)。主服務器記錄所有更改操作到二進制日志中,從服務器讀取這些日志并執(zhí)行相應的SQL語句來保持與主服務器的數(shù)據(jù)一致。
- 延遲問題:由于網(wǎng)絡傳輸和處理時間,從庫可能會有短暫的數(shù)據(jù)滯后,這對于需要實時一致性的場景是一個挑戰(zhàn)。
2. 讀寫分離
- 目的:提高系統(tǒng)性能和可用性。通過將讀請求分配給從庫,寫請求發(fā)送給主庫,可以減少主庫的壓力,提升系統(tǒng)的整體性能。
- 實現(xiàn)方式:可以通過數(shù)據(jù)庫中間件或框架層面的配置來實現(xiàn)。在這個例子中,我們使用Apache ShardingSphere來實現(xiàn)讀寫分離。
3. 自動故障轉(zhuǎn)移
- 原理:當檢測到主庫不可用時,系統(tǒng)會自動選擇一個從庫作為新的主庫,并重新調(diào)整讀寫分配。這通常涉及到心跳檢測、狀態(tài)監(jiān)控等機制。
- 工具支持:除了ShardingSphere外,還可以使用MHA(MySQL Master High Availability)或其他高可用解決方案。
實現(xiàn)步驟詳解
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. 配置數(shù)據(jù)源
編輯application.yml
文件以配置多個數(shù)據(jù)源,并設置ShardingSphere規(guī)則以實現(xiàn)讀寫分離:
深色版本
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 # 數(shù)據(jù)源名稱 master-data-source-name: master # 主庫數(shù)據(jù)源名稱 slave-data-source-names: slave0,slave1 # 從庫數(shù)據(jù)源名稱列表 props: sql: show: true # 是否顯示SQL語句
3. 配置MyBatis
創(chuàng)建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會選擇其中一個從庫來執(zhí)行查詢。 * * @return 用戶信息列表 */ @Select("SELECT * FROM users") List<Map<String, Object>> findAllUsers(); /** * 更新用戶信息. * 注意:寫操作只會針對主庫執(zhí)行。 * * @param id 用戶ID * @param newName 新用戶名 */ void updateUserById(@Param("id") Long id, @Param("newName") String newName); }
確保你的Spring Boot應用掃描到Mapper接口??梢栽谥黝惿咸砑?code>@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進行數(shù)據(jù)庫操作
現(xiàn)在你可以在Service層中注入并使用Mapper接口來進行數(shù)據(jù)庫操作:
深色版本
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); } }
注意事項及最佳實踐
- 事務管理:確保所有寫操作都在同一個事務中執(zhí)行,并且只對主庫進行寫操作。可以使用
@Transactional
注解來管理事務。 - 數(shù)據(jù)一致性:考慮到主從復制延遲的問題,在某些場景下(如剛完成寫操作后立即讀?。?,可能需要直接查詢主庫以保證數(shù)據(jù)一致性。
- 健康檢查:建議定期監(jiān)控主從狀態(tài),確保從庫同步正常以及主庫可訪問。可以通過定時任務或者外部工具來實現(xiàn)。
- 性能優(yōu)化:根據(jù)實際業(yè)務需求調(diào)整負載均衡策略,例如采用權重輪詢或其他高級算法來優(yōu)化查詢效率。
到此這篇關于Spring Boot項目中結合MyBatis實現(xiàn)MySQL的自動主從切換的文章就介紹到這了,更多相關Spring Boot MyBatis自動主從切換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot?將配置文件掛到?jar?包外面的操作方法
在 SpringBoot 中,可以將配置文件放在 jar 包外面,這樣可以方便地修改配置而不需要重新打包和部署,這篇文章主要介紹了SpringBoot?如何將配置文件掛到?jar?包外面,需要的朋友可以參考下2023-03-03Java多線程之scheduledThreadPool的方法解析
這篇文章主要介紹了Java多線程之scheduledThreadPool的方法解析,queue是DelayedWorkQueue,但通過后面的分析可以知道,最大線程數(shù)是不起作用的,最多會起核心線程數(shù)的數(shù)量,需要的朋友可以參考下2023-12-12基于Spring AMQP實現(xiàn)消息隊列的示例代碼
Spring AMQP作為Spring框架的一部分,是一套用于支持高級消息隊列協(xié)議(AMQP)的工具,AMQP是一種強大的消息協(xié)議,旨在支持可靠的消息傳遞,本文給大家介紹了如何基于Spring AMQP實現(xiàn)消息隊列,需要的朋友可以參考下2024-03-03在Java中將jsonObject轉(zhuǎn)換成對象的實現(xiàn)方法
在現(xiàn)代的Web開發(fā)中,JSON作為一種輕量級的數(shù)據(jù)交換格式,因其易讀性和易于解析的特點而被廣泛使用,本文將介紹如何在Java中將??jsonObject??轉(zhuǎn)換成Java對象,主要通過使用Gson庫來實現(xiàn)這一功能,需要的朋友可以參考下2025-04-04