# Sharding JDBC分表怎么配置
## 一、ShardingSphere與Sharding JDBC簡介
### 1.1 ShardingSphere生態體系
Apache ShardingSphere是一套開源的分布式數據庫中間件解決方案組成的生態圈,包含以下核心組件:
- **Sharding JDBC**:輕量級Java框架,提供分庫分表能力
- **Sharding Proxy**:透明化的數據庫代理端
- **Sharding Sidecar**(規劃中):云原生數據庫代理
### 1.2 Sharding JDBC核心特性
1. 分庫分表(水平拆分)
2. 讀寫分離
3. 分布式事務
4. 數據脫敏
5. 分布式主鍵
6. 彈性伸縮能力
## 二、分表配置基礎概念
### 2.1 分表策略類型
| 策略類型 | 描述 | 適用場景 |
|----------------|-----------------------------|------------------------|
| 標準分片策略 | 基于=、IN、BETWEEN的分片 | 精確查詢場景 |
| 復合分片策略 | 多分片鍵組合 | 多維度查詢需求 |
| 行表達式分片策略 | Groovy表達式配置 | 簡單分片規則 |
| Hint分片策略 | 通過Hint指定分片 | 特殊路由場景 |
### 2.2 核心配置元素
```yaml
sharding:
tables:
[邏輯表名]:
actual-data-nodes: # 物理表節點
table-strategy: # 分表策略
standard: # 標準策略
sharding-column: # 分片字段
precise-algorithm-class-name: # 精確分片算法
spring:
shardingsphere:
datasource:
names: ds0
ds0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/demo_ds?serverTimezone=UTC
username: root
password:
sharding:
tables:
t_order:
actual-data-nodes: ds0.t_order_$->{0..15}
table-strategy:
inline:
sharding-column: order_id
algorithm-expression: t_order_$->{order_id % 16}
key-generator:
column: order_id
type: SNOWFLAKE
props:
worker.id: 123
actual-data-nodes:
ds0.t_order_$->{0..15}
表示16個分片表分片算法配置:
table-strategy:
complex:
sharding-columns: user_id,order_date
algorithm-class-name: com.example.MyComplexShardingAlgorithm
public DataSource getDataSource() throws SQLException {
// 數據源配置
Map<String, DataSource> dataSourceMap = new HashMap<>();
dataSourceMap.put("ds0", createDataSource("ds0"));
// 分表規則
ShardingTableRuleConfiguration tableRuleConfig = new ShardingTableRuleConfiguration(
"t_order",
"ds0.t_order_$->{0..15}");
// 分片算法配置
Properties props = new Properties();
props.setProperty("algorithm-expression", "t_order_$->{order_id % 16}");
tableRuleConfig.setTableShardingStrategy(
new StandardShardingStrategyConfiguration(
"order_id",
"inline",
props));
// 主鍵生成配置
tableRuleConfig.setKeyGeneratorConfig(new KeyGeneratorConfiguration("SNOWFLAKE", "order_id"));
// 全局配置
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTables().add(tableRuleConfig);
return ShardingSphereDataSourceFactory.createDataSource(
dataSourceMap,
Collections.singleton(shardingRuleConfig),
new Properties());
}
行表達式分片(inline)
algorithm-expression: t_order_$->{order_id % 8}
標準分片算法
public class OrderIdPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Long> {
@Override
public String doSharding(Collection<String> tableNames, PreciseShardingValue<Long> shardingValue) {
return "t_order_" + (shardingValue.getValue() % 16);
}
}
范圍分片算法
public class OrderIdRangeShardingAlgorithm implements RangeShardingAlgorithm<Long> {
@Override
public Collection<String> doSharding(Collection<String> tableNames,
RangeShardingValue<Long> shardingValue) {
// 處理BETWEEN AND查詢的路由
}
}
table-strategy:
complex:
sharding-columns: user_id,order_date
algorithm-class-name: com.example.MultiKeyShardingAlgorithm
sharding:
binding-tables:
- t_order,t_order_item
sharding:
broadcast-tables:
- t_config
sharding:
tables:
t_order:
key-generator:
column: order_id
type: SNOWFLAKE
props:
worker.id: 123
max.tolerate.time.difference.milliseconds: 60000
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>5.1.1</version>
</dependency>
# 開啟SQL顯示
spring.shardingsphere.props.sql.show=true
# 數據源配置
spring.shardingsphere.datasource.names=ds0
spring.shardingsphere.datasource.ds0.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.ds0.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.ds0.jdbc-url=jdbc:mysql://localhost:3306/demo_ds
spring.shardingsphere.datasource.ds0.username=root
// 正確方式(分片鍵條件分頁) select * from t_order where order_id > 100000 limit 10;
## 七、常見問題排查
### 7.1 典型錯誤場景
1. **SQL不支持異常**:
- 原因:使用了不支持的SQL語法(如多子查詢)
- 方案:簡化SQL或使用Hint強制路由
2. **分片鍵缺失**:
```java
// 錯誤示例
@Query("SELECT * FROM t_order WHERE status = :status")
List<Order> findByStatus(@Param("status") String status);
// 正確示例
@Query("SELECT * FROM t_order WHERE order_id = :orderId AND status = :status")
List<Order> findByIdAndStatus(@Param("orderId") Long orderId,
@Param("status") String status);
spring.shardingsphere.props.sql.show=true
[INFO ] - Actual SQL: ds0 ::: SELECT * FROM t_order_3 WHERE order_id = ?
sharding.jdbc
改為spring.shardingsphere
ShardingSphereYamlSwapper swapper = new YamlShardingRuleConfigurationSwapper();
ShardingRuleConfiguration config = swapper.swap(yamlConfig);
通過本文的詳細講解,您應該已經掌握了Sharding JDBC分表配置的核心方法。實際應用中建議: 1. 開發環境開啟SQL日志驗證路由準確性 2. 生產環境做好分片算法的壓力測試 3. 歷史數據遷移考慮使用ShardingSphere-Scaling工具 4. 持續關注社區版本更新
官方文檔參考:https://shardingsphere.apache.org/document/current/cn/overview/ “`
注:本文檔示例基于ShardingSphere 5.1.1版本,實際使用時請根據具體版本調整配置語法。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。