Redis Cluster槽位分配机制
Redis Cluster将数据空间划分为16384个哈希槽,每个键通过CRC16校验后对16384取模确定所属槽位。集群中的每个主节点负责一部分槽位。当集群扩容或缩容时需要在节点间迁移槽位,这个过程就是重平衡。
# 查看集群节点和槽位分配
redis-cli --cluster info 10.0.0.1:6379
# 查看每个节点的槽位范围
redis-cli -c -h 10.0.0.1 -p 6379 cluster nodes
# 查看指定键所属的槽位
redis-cli -c -h 10.0.0.1 -p 6379 cluster keyslot "user:1001"
槽位迁移的本质是将源节点中的部分键从源节点迁移到目标节点。迁移过程中涉及的槽位处于迁出中状态,源节点标记为importing,目标节点标记为migrating。
在线迁移槽位的操作步骤
# 自动迁移1000个槽位
redis-cli --cluster reshard 10.0.0.1:6379 --cluster-from node1_id --cluster-to node4_id --cluster-slots 1000 --cluster-yes
手动迁移单个槽位的底层操作流程:
# 1. 在目标节点设置importing状态
redis-cli -h 10.0.0.4 -p 6379 cluster setslot 1000 importing node1_id
# 2. 在源节点设置migrating状态
redis-cli -h 10.0.0.1 -p 6379 cluster setslot 1000 migrating node4_id
# 3. 获取槽位1000的所有键
redis-cli -h 10.0.0.1 -p 6379 cluster getkeysinslot 1000 100
# 4. 逐个迁移键
redis-cli -h 10.0.0.1 -p 6379 migrate 10.0.0.4 6379 "" 0 5000 KEYS key1 key2 key3
# 5. 通知所有节点槽位迁移完成
redis-cli -h 10.0.0.1 -p 6379 cluster setslot 1000 node node4_id
migrate命令是原子操作,迁移过程中键在源节点会被短暂锁定但整体服务不受影响。
迁移期间的请求处理与ASK重定向
槽位迁移期间客户端的请求路由遵循以下规则:键在源节点时直接处理;键已迁移到目标节点时源节点返回ASK重定向;迁移完成后客户端收到MOVED重定向更新本地缓存。Jedis/Lettuce和go-redis等客户端都自动处理ASK/MOVED重定向。
# 监控重定向指标
redis-cli -h 10.0.0.1 -p 6379 info stats | grep -i redirect
大规模重平衡的性能调优
关键调优参数包括:迁移超时时间(migrate命令超时参数默认5秒,大key需增大)、批量大小(每次迁移的键数量)、迁移间隔(每批次之间的暂停时间)。
#!/bin/bash
SOURCE_HOST="10.0.0.1"
SOURCE_PORT=6379
TARGET_HOST="10.0.0.4"
TARGET_PORT=6379
SLOTS=(0 1 2 3 4 5 6 7 8 9)
for slot in "${SLOTS[@]}"; do
keys=$(redis-cli -h $SOURCE_HOST -p $SOURCE_PORT cluster getkeysinslot $slot 100)
if [ -n "$keys" ]; then
redis-cli -h $SOURCE_HOST -p $SOURCE_PORT migrate $TARGET_HOST $TARGET_PORT "" 0 10000 KEYS $keys
fi
redis-cli -h $SOURCE_HOST -p $SOURCE_PORT cluster setslot $slot node $(redis-cli -h $TARGET_HOST -p $TARGET_PORT cluster myid)
sleep 0.5
done
迁移失败回滚与数据一致性校验
槽位迁移过程中可能出现网络中断、目标节点宕机等异常。Redis的迁移机制保证数据不丢——键要么在源节点要么在目标节点。
# 检查处于迁移状态的槽位
redis-cli -h 10.0.0.1 -p 6379 cluster nodes | grep -E "migrating|importing"
# 如果迁移中断重置中间状态
redis-cli --cluster fix 10.0.0.1:6379
# 撤销迁移
redis-cli -h 10.0.0.4 -p 6379 cluster setslot 1000 stable
redis-cli -h 10.0.0.1 -p 6379 cluster setslot 1000 stable
数据一致性校验使用redis-cli –cluster check命令。生产环境的迁移窗口建议选在业务低峰时段,迁移速度控制在每秒100-500个键,出现延迟抖动时暂停迁移。
原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/rediscluster-shu-ju-qian-yi-yu-cao-wei-zhong-ping-heng-cao/