Mycat2 分片策略
分片算法概述
Mycat2 支持可插拔的分片算法框架,以下为内置分片算法:
| 算法 | Class | 说明 |
|---|---|---|
| 取模分片 | PartitionByMod | 对分片键取模 |
| 固定哈希分片 | PartitionByLong | 固定分片哈希 |
| MurmurHash分片 | PartitionByMurmurHash | 一致性哈希 |
| 范围分片 | PartitionByRangeMod | 范围取模组合 |
| 日期分片 | PartitionByDate | 按日期分片 |
| 枚举分片 | PartitionByFileMap | 枚举映射 |
| 字符串哈希 | PartitionByString | 字符串哈希取模 |
| CRC32Slot | PartitionByCRC32PreSlot | CRC32预分槽算法 |
1. 取模分片
{
"function": {
"clazz": "io.mycat.router.function.PartitionByMod",
"properties": {
"count": 4
}
},
"shardingFunc": {
"function": { "clazz": "...PartitionByMod", "properties": {"count": 4} },
"tableMatcher": "db1.travelrecord",
"columnName": "id",
"version": "1"
}
}
2. 一致性哈希 (MurmurHash)
{
"function": {
"clazz": "io.mycat.router.function.PartitionByMurmurHash",
"properties": {
"seed": 0,
"count": 4,
"virtualBucketTimes": 160
}
}
}
3. 日期分片
{
"function": {
"clazz": "io.mycat.router.function.PartitionByDate",
"properties": {
"dateFormat": "yyyy-MM-dd",
"sBeginDate": "2026-01-01",
"sEndDate": "2026-12-31",
"sPartionDay": 30
}
}
}
4. 范围取模分片
{
"function": {
"clazz": "io.mycat.router.function.PartitionByRangeMod",
"properties": {
"defaultNode": 0,
"mapFile": "partition-range-mod.txt"
}
}
}
# partition-range-mod.txt
0-2000=0
2001-4000=1
4001-6000=2
5. 枚举分片
{
"function": {
"clazz": "io.mycat.router.function.PartitionByFileMap",
"properties": {
"type": "Integer",
"defaultNode": -1,
"mapFile": "sharding-by-enum.txt"
}
}
}
# sharding-by-enum.txt
10000=0
10010=1
6. CRC32 预分槽算法
{
"function": {
"clazz": "io.mycat.router.function.PartitionByCRC32PreSlot",
"properties": {
"count": 1024
}
}
}
自定义分片算法
实现 io.mycat.router.function.ShardingFunction 接口即可:
public class MyShardingFunction implements ShardingFunction {
@Override
public int calculate(String columnValue) {
// 自定义分片逻辑
int hash = Math.abs(columnValue.hashCode());
return hash % nodeCount;
}
@Override
public void init(Properties properties) {
// 读取配置参数
}
}
负载均衡算法
| 算法 | 说明 |
|---|---|
| BalanceLeastActive | 最小活跃连接数 |
| BalanceRandom | 随机 |
| BalanceRoundRobin | 轮询 |
| BalanceRunOnMaster | 只在主节点执行 |
| BalanceAllRead | 所有读节点 |
提示: Mycat2的分片算法支持热加载。放置在
lib/ 目录下的自定义JAR包会自动扫描加载。