您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。