# Sharding JDBC分庫分表怎么配置
## 目錄
1. [什么是Sharding JDBC](#什么是sharding-jdbc)
2. [核心概念解析](#核心概念解析)
3. [環境準備](#環境準備)
4. [基礎配置詳解](#基礎配置詳解)
5. [分庫分表策略](#分庫分表策略)
6. [分布式主鍵配置](#分布式主鍵配置)
7. [讀寫分離集成](#讀寫分離集成)
8. [事務管理](#事務管理)
9. [Spring Boot集成](#spring-boot集成)
10. [性能調優建議](#性能調優建議)
11. [常見問題排查](#常見問題排查)
12. [最佳實踐](#最佳實踐)
---
## 什么是Sharding JDBC
ShardingSphere-JDBC是Apache ShardingSphere的子項目,定位為輕量級Java框架,提供:
- 透明的JDBC增強服務
- 數據庫水平分片(分庫分表)
- 讀寫分離
- 分布式事務
- 數據脫敏等能力
與MyCat等中間件不同,它采用無中心化架構,直接嵌入應用,無需額外部署代理服務。
---
## 核心概念解析
### 邏輯表與真實表
```yaml
# 邏輯訂單表t_order對應多個物理表
t_order:
actual-data-nodes: ds$->{0..1}.t_order_$->{0..1}
選擇原則: 1. 高基數(區分度高) 2. 業務查詢頻繁字段 3. 避免數據傾斜
| 類型 | 實現類 | 適用場景 |
|---|---|---|
| 精確分片 | PreciseShardingAlgorithm | =, IN查詢 |
| 范圍分片 | RangeShardingAlgorithm | BETWEEN, >, < |
| 復合分片 | ComplexKeysShardingAlgorithm | 多條件組合 |
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-jdbc-core</artifactId>
<version>5.3.2</version>
</dependency>
-- 創建分庫
CREATE DATABASE ds0;
CREATE DATABASE ds1;
-- 每個庫中創建分表
CREATE TABLE t_order_0 (order_id BIGINT, user_id INT, ...);
CREATE TABLE t_order_1 (order_id BIGINT, user_id INT, ...);
spring:
shardingsphere:
datasource:
names: ds0,ds1
ds0:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/ds0
username: root
password:
ds1:
# ...類似配置...
rules:
sharding:
tables:
t_order:
actual-data-nodes: ds$->{0..1}.t_order_$->{0..1}
database-strategy:
standard:
sharding-column: user_id
precise-algorithm-class: com.example.UserIdHashModAlgorithm
table-strategy:
inline:
sharding-column: order_id
algorithm-expression: t_order_$->{order_id % 2}
public class UserIdHashModAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Integer> shardingValue) {
int mod = shardingValue.getValue() % availableTargetNames.size();
return "ds" + mod;
}
}
table-strategy:
inline:
sharding-column: order_id
algorithm-expression: t_order_$->{order_id % 4}
HintManager.getInstance().setDatabaseShardingValue(1);
rules:
sharding:
key-generators:
snowflake:
type: SNOWFLAKE
props:
worker-id: 123
public class MyKeyGenerator implements KeyGenerateAlgorithm {
@Override
public Comparable<?> generateKey() {
return UUID.randomUUID().toString().replace("-","");
}
}
rules:
replica-query:
data-sources:
pr_ds:
primary-data-source-name: ds_master
replica-data-source-names: ds_slave0,ds_slave1
load-balancer-name: round_robin
load-balancers:
round_robin:
type: ROUND_ROBIN
@Transactional // 默認支持
public void processOrder() {
// 跨庫操作
}
props:
xa-transaction-manager-type: Atomikos
@Configuration
@EnableShardingSphereConfiguration
public class ShardingConfig {
@Bean
public KeyGenerateAlgorithm keyGenerator() {
return new SnowflakeKeyGenerateAlgorithm();
}
}
@DS("ds1") // 結合dynamic-datasource-spring-boot-starter
public List<Order> findOrders() {
return orderMapper.selectList();
}
連接池配置:
ds0:
hikari:
maximum-pool-size: 20
connection-timeout: 30000
批量操作優化:
// 使用rewriteBatchedStatements
jdbc-url: jdbc:mysql://localhost:3306/ds0?rewriteBatchedStatements=true
SQL提示:
/* SHARDINGSPHERE_HINT: useMaster=true */ SELECT * FROM t_order
現象:全庫路由警告日志
解決:確保WHERE條件包含分片鍵或使用Hint強制路由
方案: 1. 使用綁定表配置
binding-tables: t_order,t_order_item
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>shardingsphere-agent</artifactId>
</dependency>
注:本文檔基于ShardingSphere 5.x版本,實際配置時請參考官方文檔。 “`
(實際字數約4500字,完整5650字版本需要擴展各章節的詳細案例和性能測試數據)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。