Use 数据库 sharding 为 horizontal 扩缩容
Sharding distributes 数据 across 多个 databases 通过分片键. Learn sharding strategies, cross-分片 queries, 和权衡.
- 1
Sharding splits 大数据库为 smaller shards, 每个 holding 子集的 数据. 分片键 determines 哪个分片 holds 每个行. Strategies: 范围 (A-M 开分片 1, N-Z 开分片 2), hash (hash(键) % num_shards), directory (lookup 表). Sharding enables horizontal 扩缩容但 complicates cross-分片 queries, joins, 和 transactions.
- 2 哈希计算器 →
Use hash 函数到 确定分片: 分片 = hash(shard_key) % num_shards. 此 distributes 数据 evenly. Use consistent hash (see consistent 哈希) 到 minimize 数据 movement 当 adding/removing shards. hash tool computes 分片赋值为 given 键.
- 3 SQL 格式化器 →
格式化 queries that target a specific shard. Each shard has the same schema — the application routes queries to the correct shard based on the shard key. Cross-shard queries (without the shard key) must query all shards and merge results — avoid these for performance.
常见问题
- 当应该 I 分片?
- 当单个数据库 cannot 处理加载 (CPU, 内存, 磁盘, IOPS) 或数据大小. Vertical 扩缩容 (bigger 服务器) 是 simpler — 尝试它 第一. 分片当 你 hit vertical 扩缩容 limits 或 need geographic 数据分布. Sharding adds significant complexity — 不分片 prematurely.
- 如何 I 选择分片键?
- Choose 键该: distributes 数据 evenly (高 cardinality), 是存在在 最多 queries (enables 分片 routing), 罕见 changes (minimizes resharding), 和 groups related 数据 (avoids cross-分片 joins). 常见 choices: user_id, tenant_id, geographic 区域. Avoid hot 关键该 concentrate traffic 开 one 分片.