您好,登錄后才能下訂單哦!
本篇內容主要講解“SpringBoot怎么整合sharding-jdbc實現分庫分表與讀寫分離”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“SpringBoot怎么整合sharding-jdbc實現分庫分表與讀寫分離”吧!
本文將基于以下環境整合sharding-jdbc
實現分庫分表
與讀寫分離
springboot2.4.0
mybatis-plus3.4.3.1
mysql5.7主從
溫馨小提示:此sql執行時,如果之前有存在相應庫和表會進行自動刪除后再創建!
DROP DATABASE IF EXISTS ds0; CREATE DATABASE ds0; USE ds0; SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for t_user0 -- ---------------------------- DROP TABLE IF EXISTS `t_user0`; CREATE TABLE `t_user0` ( `user_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主鍵ID', `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用戶名', `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密碼', `sex` tinyint(4) NULL DEFAULT NULL COMMENT '性別', `remark` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '備注', PRIMARY KEY (`user_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用戶' ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for t_user1 -- ---------------------------- DROP TABLE IF EXISTS `t_user1`; CREATE TABLE `t_user1` ( `user_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主鍵ID', `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用戶名', `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密碼', `sex` tinyint(4) NULL DEFAULT NULL COMMENT '性別', `remark` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '備注', PRIMARY KEY (`user_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用戶' ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; -- =============================================================================================== DROP DATABASE IF EXISTS ds1; CREATE DATABASE ds1; USE ds1; SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for t_user0 -- ---------------------------- DROP TABLE IF EXISTS `t_user0`; CREATE TABLE `t_user0` ( `user_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主鍵ID', `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用戶名', `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密碼', `sex` tinyint(4) NULL DEFAULT NULL COMMENT '性別', `remark` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '備注', PRIMARY KEY (`user_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用戶' ROW_FORMAT = Dynamic; -- ---------------------------- -- Table structure for t_user1 -- ---------------------------- DROP TABLE IF EXISTS `t_user1`; CREATE TABLE `t_user1` ( `user_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主鍵ID', `username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用戶名', `password` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '密碼', `sex` tinyint(4) NULL DEFAULT NULL COMMENT '性別', `remark` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '備注', PRIMARY KEY (`user_id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci COMMENT = '用戶' ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1;
1、pom
中引入依賴
<!-- sharding-jdbc --> <!-- https://mvnrepository.com/artifact/org.apache.shardingsphere/sharding-jdbc-spring-boot-starter --> <dependency> <groupId>org.apache.shardingsphere</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>4.1.1</version> </dependency>
2、application.yml
配置
spring: # sharding-jdbc配置 shardingsphere: # 是否開啟SQL顯示 props: sql: show: true # ====================== ↓↓↓↓↓↓ 數據源配置 ↓↓↓↓↓↓ ====================== datasource: names: ds-master-0,ds-slave-0-1,ds-slave-0-2,ds-master-1,ds-slave-1-1,ds-slave-1-2 # ====================== ↓↓↓↓↓↓ 配置第1個主從庫 ↓↓↓↓↓↓ ====================== # 主庫1 ds-master-0: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3306/ds0?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否進行SSL連接 解決則加上 &useSSL=false username: root password: root # 主庫1-從庫1 ds-slave-0-1: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3307/ds0?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否進行SSL連接 解決則加上 &useSSL=false username: root password: root # 主庫1-從庫2 ds-slave-0-2: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3307/ds0?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否進行SSL連接 解決則加上 &useSSL=false username: root password: root # ====================== ↓↓↓↓↓↓ 配置第2個主從庫 ↓↓↓↓↓↓ ====================== # 主庫2 ds-master-1: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3306/ds1?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否進行SSL連接 解決則加上 &useSSL=false username: root password: root # 主庫2-從庫1 ds-slave-1-1: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3307/ds1?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否進行SSL連接 解決則加上 &useSSL=false username: root password: root # 主庫2-從庫2 ds-slave-1-2: type: com.zaxxer.hikari.HikariDataSource driver-class-name: com.mysql.jdbc.Driver jdbc-url: jdbc:mysql://127.0.0.1:3307/ds1?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否進行SSL連接 解決則加上 &useSSL=false username: root password: root sharding: # ====================== ↓↓↓↓↓↓ 分庫分表配置 ↓↓↓↓↓↓ ====================== # 分庫策略 => 根據user_id取模拆分到不同的庫中 default-database-strategy: inline: sharding-column: user_id algorithm-expression: ds-master-$->{user_id % 2} # 分表策略 tables: t_user: actual-data-nodes: ds-master-$->{0..1}.t_user$->{0..1} key-generator: column: user_id # 主鍵ID type: SNOWFLAKE # 生成策略 # 添加數據分表策略 table-strategy: inline: # 添加數據分表字段(根據字段插入數據到那個表 ex:sex) sharding-column: sex # 分片算法表達式 => 根據用戶性別取模拆分到不同的表中 algorithm-expression: t_user$->{sex % 2} # ====================== ↓↓↓↓↓↓ 讀寫分離配置 ↓↓↓↓↓↓ ====================== master-slave-rules: ds-master-0: # 主庫 masterDataSourceName: ds-master-0 # 從庫 slaveDataSourceNames: - ds-slave-0-1 - ds-slave-0-2 # 從庫查詢數據的負載均衡算法 目前有2種算法 round_robin(輪詢)和 random(隨機) # 算法接口 org.apache.shardingsphere.spi.masterslave.MasterSlaveLoadBalanceAlgorithm # 實現類 RandomMasterSlaveLoadBalanceAlgorithm 和 RoundRobinMasterSlaveLoadBalanceAlgorithm loadBalanceAlgorithmType: ROUND_ROBIN ds-master-1: masterDataSourceName: ds-master-1 slaveDataSourceNames: - ds-slave-1-1 - ds-slave-1-2 loadBalanceAlgorithmType: ROUND_ROBIN
3、引入sharding-jdbc后數據源健康配置
解決啟動報錯問題: ConnectionCallback; isValid; nested exception is java.sql.SQLFeatureNotSupportedException: isValid
原因: springboot2.4數據源健康檢查
@Configuration public class DataSourceHealthConfig extends DataSourceHealthContributorAutoConfiguration { @Value("${spring.datasource.dbcp2.validation-query:select 1}") private String defaultQuery; public DataSourceHealthConfig(Map<String, DataSource> dataSources, ObjectProvider<DataSourcePoolMetadataProvider> metadataProviders) { super(dataSources, metadataProviders); } @Override protected AbstractHealthIndicator createIndicator(DataSource source) { DataSourceHealthIndicator indicator = (DataSourceHealthIndicator) super.createIndicator(source); if (!StringUtils.hasText(indicator.getQuery())) { indicator.setQuery(defaultQuery); } return indicator; } }
到此配置完成,然后就可以自己編寫CRUD進行測試了,配置比較簡單,屬于入門篇
# 環境準備 git clone https://gitee.com/zhengqingya/docker-compose.git cd docker-compose/Liunx # 運行 docker-compose -f docker-compose-mysql-master-slave.yml -p mysql-master-slave up -d
# ================== ↓↓↓↓↓↓ 配置主庫 ↓↓↓↓↓↓ ================== # 進入主庫 docker exec -it mysql_master /bin/bash # 登錄mysql mysql -uroot -proot # 創建用戶slave,密碼123456 CREATE USER 'slave'@'%' IDENTIFIED BY '123456'; # 授予slave用戶 `REPLICATION SLAVE`權限和`REPLICATION CLIENT`權限,用于在`主` `從` 數據庫之間同步數據 GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'slave'@'%'; # 授予所有權限則執行命令: GRANT ALL PRIVILEGES ON *.* TO 'slave'@'%'; # 使操作生效 FLUSH PRIVILEGES; # 查看狀態 show master status; # 注:File和Position字段的值slave中將會用到,在slave操作完成之前不要操作master,否則將會引起狀態變化,即File和Position字段的值變化 !!! # +------------------+----------+--------------+------------------+-------------------+ # | File | Position | Binlog_Do_DB | Binlog_Ignore_DB | Executed_Gtid_Set | # +------------------+----------+--------------+------------------+-------------------+ # | mysql-bin.000003 | 769 | | | | # +------------------+----------+--------------+------------------+-------------------+ # 1 row in set (0.00 sec) # ================== ↓↓↓↓↓↓ 配置從庫 ↓↓↓↓↓↓ ================== # 進入從庫 docker exec -it mysql_slave /bin/bash # 登錄mysql mysql -uroot -proot change master to master_host='www.zhengqingya.com',master_port=3306, master_user='slave', master_password='123456', master_log_file='mysql-bin.000003', master_log_pos= 769, master_connect_retry=30; # 開啟主從同步過程 【停止命令:stop slave;】 start slave; # 查看主從同步狀態 show slave status \G # Slave_IO_Running 和 Slave_SQL_Running 都是Yes的話,就說明主從同步已經配置好了! # 如果Slave_IO_Running為Connecting,SlaveSQLRunning為Yes,則說明配置有問題,這時候就要檢查配置中哪一步出現問題了哦,可根據Last_IO_Error字段信息排錯或谷歌… # *************************** 1. row *************************** # Slave_IO_State: Waiting for master to send event # Master_Host: www.zhengqingya.com # Master_User: slave # Master_Port: 3306 # Connect_Retry: 30 # Master_Log_File: mysql-bin.000003 # Read_Master_Log_Pos: 769 # Relay_Log_File: c598d8402b43-relay-bin.000002 # Relay_Log_Pos: 320 # Relay_Master_Log_File: mysql-bin.000003 # Slave_IO_Running: Yes # Slave_SQL_Running: Yes # Replicate_Do_DB:
到此,相信大家對“SpringBoot怎么整合sharding-jdbc實現分庫分表與讀寫分離”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。