前言
ShardingSphere可以支撐分庫分表,剛果商城采用了垂直分庫(根據不同業務拆分數據庫),因此此文章只演示水平分表。
垂直分庫
不同業務拆分為不同的數據庫(例如商城業務)
水平分表
分表可以通過將大表拆分為多個小表,減少單表的數據量,從而提高查詢性能。好處比較多…
分表命名格式最好為邏輯表_num
這個格式,方便后續操作
介紹完基本的概念,開始實踐。
ShardingSphere官方文檔
接下來重點關注分片算法
和加密算法
核心依賴
我這里使用的是5.2.0版本
<dependency><groupId>org.apache.shardingsphere</groupId><artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId><version>5.2.0</version></dependency>
配置文件(核心)
spring:shardingsphere:datasource:# 為每個數據源進行配置,有幾個配幾個ds-0:driver-class-name: com.mysql.jdbc.Drivertype: com.zaxxer.hikari.HikariDataSource# 配置數據源,可以配置多個names: ds-0props:# 打印sql日志方便觀察sql-show: truemax-connections-size-per-query: 10rules:encrypt:encryptors:# 自定義加密算法名稱customer-user-encryptor:props:# AES 使用的 KEYaes-key-value: ADbisulBtxnnKFoWtype: AEStables:# 指定表相應字段加密算法customer_user:# 加密字段columns:mail:cipher-column: mailencryptor-name: customer-user-encryptorphone:cipher-column: phoneencryptor-name: customer-user-encryptorreceive_address:columns:phone:cipher-column: phoneencryptor-name: customer-user-encryptordetail_address:cipher-column: detail_addressencryptor-name: customer-user-encryptorsharding:sharding-algorithms:# 自定義分片算法名稱 哈希取模分片算法 對 16 取余sharding_by_mod:props:sharding-count: 16type: HASH_MOD # hash算法tables:# 不同表配置分片算法customer_user:# 指定真實表表名稱 `$->{0..15}` 即 0-15actual-data-nodes: ds-0.customer_user_$->{0..15}table-strategy:standard:sharding-algorithm-name: sharding_by_modsharding-column: id # 分片字段operation_log:actual-data-nodes: ds-0.operation_log_$->{0..15}table-strategy:standard:sharding-algorithm-name: sharding_by_modsharding-column: customer_user_idreceive_address:actual-data-nodes: ds-0.receive_address_$->{0..15}table-strategy:standard:sharding-algorithm-name: sharding_by_modsharding-column: customer_user_id
分片算法
:
加密算法
:
代碼實踐
配置完之后,使用起來就很簡單了,只需將實體類指定邏輯表名稱
,使用起來是無感知的。
測試一下
調用【新增用戶】接口。
入參:
執行時,會發現有個邏輯SQL
和實際SQL
,可以看到當前用戶通過配置的Hash分片算法
,被分配到了customer_user_5表中
同時加密算法也起了作用,phone和mail字段都被加密。
ShardingSphere
使用起來就是這么滴簡單。希望這篇文章對大家有幫助,有什么錯誤可以聯系(私信)博主改正。
歡迎大家點贊 + 收藏 + 關注。
關注小李不迷路~
詳細分庫分表內容可以看我這篇博客 MySQL與分布式