Redis Sentinel解决高可用问题(主宕机自动切换),Redis Cluster同时解决高可用和横向扩展问题——将数据自动分片到多个主节点,每个主节点配备从节点实现故障转移。当单机Redis内存不足或QPS超过上限时,Cluster是必然选择。
一、Redis Cluster核心概念
<code">Redis Cluster架构(三主三从,最小生产配置):
master-1 (slot 0~5460) ←→ slave-1(master-1的副本)
master-2 (slot 5461~10922) ←→ slave-2(master-2的副本)
master-3 (slot 10923~16383) ←→ slave-3(master-3的副本)
数据分片规则:
key → CRC16(key) % 16384 → 落到对应slot → 路由到对应master
HashTag(强制相关数据到同一slot):
key: {user:1}:profile → 取{}内的user:1计算hash
key: {user:1}:orders → 同样取user:1,保证在同一节点
适用场景:需要对同一用户的多个key做原子操作时二、六节点Redis Cluster部署
<code">mkdir -p /srv/redis-cluster && cd /srv/redis-cluster
# 为6个节点创建配置目录
for port in 7001 7002 7003 7004 7005 7006; do
mkdir -p data/$port
done<code"># 生成节点配置(以7001为例,其他节点修改port和cluster-announce-port)
cat_config() {
local port=$1
cat > config/$port.conf << EOF
port $port
cluster-enabled yes
cluster-config-file /data/nodes-${port}.conf
cluster-node-timeout 5000
cluster-announce-ip $(hostname -I | awk '{print $1}')
cluster-announce-port $port
cluster-announce-bus-port $((port + 10000))
appendonly yes
appendfilename "appendonly-${port}.aof"
dir /data
logfile /data/redis-${port}.log
loglevel notice
protected-mode no
bind 0.0.0.0
requirepass 你的Redis密码
masterauth 你的Redis密码
maxmemory 512mb
maxmemory-policy allkeys-lru
save ""
EOF
}
for port in 7001 7002 7003 7004 7005 7006; do
mkdir -p config
cat_config $port
done<code"># docker-compose.yml(6节点集群)
version: '3.8'
x-redis-common: &redis-common
image: redis:7.2-alpine
restart: unless-stopped
networks:
- redis-cluster
services:
redis-7001:
<<: *redis-common
command: redis-server /config/7001.conf
volumes:
- ./config/7001.conf:/config/7001.conf:ro
- ./data/7001:/data
ports:
- "7001:7001"
- "17001:17001" # 集群总线端口
redis-7002:
<<: *redis-common
command: redis-server /config/7002.conf
volumes:
- ./config/7002.conf:/config/7002.conf:ro
- ./data/7002:/data
ports:
- "7002:7002"
- "17002:17002"
redis-7003:
<<: *redis-common
command: redis-server /config/7003.conf
volumes:
- ./config/7003.conf:/config/7003.conf:ro
- ./data/7003:/data
ports:
- "7003:7003"
- "17003:17003"
redis-7004:
<<: *redis-common
command: redis-server /config/7004.conf
volumes:
- ./config/7004.conf:/config/7004.conf:ro
- ./data/7004:/data
ports:
- "7004:7004"
- "17004:17004"
redis-7005:
<<: *redis-common
command: redis-server /config/7005.conf
volumes:
- ./config/7005.conf:/config/7005.conf:ro
- ./data/7005:/data
ports:
- "7005:7005"
- "17005:17005"
redis-7006:
<<: *redis-common
command: redis-server /config/7006.conf
volumes:
- ./config/7006.conf:/config/7006.conf:ro
- ./data/7006:/data
ports:
- "7006:7006"
- "17006:17006"
networks:
redis-cluster:
driver: bridge<code">docker compose up -d
# 等待所有节点启动
sleep 5
# 创建集群(3主3从,--cluster-replicas 1 表示每主1个从)
docker exec redis-cluster-redis-7001-1 \
redis-cli -a 你的Redis密码 \
--cluster create \
服务器IP:7001 服务器IP:7002 服务器IP:7003 \
服务器IP:7004 服务器IP:7005 服务器IP:7006 \
--cluster-replicas 1 \
--cluster-yes
# 验证集群状态
docker exec redis-cluster-redis-7001-1 \
redis-cli -a 你的Redis密码 \
-c -p 7001 cluster info三、集群状态管理命令
<code"># 查看集群节点信息(主从关系、slot分配) redis-cli -a 你的密码 -c -p 7001 cluster nodes # 查看集群信息摘要 redis-cli -a 你的密码 -c -p 7001 cluster info # cluster_state:ok ← 正常 # cluster_slots_assigned:16384 ← 所有slot已分配 # cluster_known_nodes:6 ← 6个节点 # 测试分片写入(-c参数开启集群模式,自动重定向) redis-cli -a 你的密码 -c -p 7001 set testkey "hello" # → Redirected to slot [4205] located at 服务器IP:7001 # OK redis-cli -a 你的密码 -c -p 7001 get testkey # "hello"
四、Node.js客户端连接
<code">// npm install ioredis
import Redis from 'ioredis';
const cluster = new Redis.Cluster([
{ host: '服务器IP', port: 7001 },
{ host: '服务器IP', port: 7002 },
{ host: '服务器IP', port: 7003 },
// ioredis会自动发现其他节点,只需配置部分节点
], {
redisOptions: {
password: '你的Redis密码',
connectTimeout: 3000,
},
clusterRetryStrategy(times) {
if (times > 3) return null; // 超过3次放弃
return Math.min(100 * times, 3000);
},
enableReadyCheck: true,
scaleReads: 'slave', // 读操作路由到从节点(降低主节点压力)
natMap: {}, // 如果Redis在Docker/NAT后面需要配置
});
// 普通操作(自动路由到正确节点)
await cluster.set('user:1:name', 'Alice');
await cluster.get('user:1:name');
// HashTag:强制相关key在同一节点(支持原子操作)
await cluster.set('{user:1}:profile', JSON.stringify({ name: 'Alice', age: 25 }));
await cluster.set('{user:1}:orders', JSON.stringify([1, 2, 3]));
// Pipeline批量操作(同一slot的key才能批量)
const pipeline = cluster.pipeline();
pipeline.get('{user:1}:profile');
pipeline.get('{user:1}:orders');
const results = await pipeline.exec();
// 监听集群事件
cluster.on('+node', (node) => console.log(`节点加入: ${node.options.host}:${node.options.port}`));
cluster.on('-node', (node) => console.log(`节点离开: ${node.options.host}:${node.options.port}`));
cluster.on('node error', (err, node) => console.error(`节点错误: ${node.options.host}`, err));
五、集群扩容(增加新节点)
<code"># 准备新主节点(7007)和从节点(7008)
# 启动后,将新节点加入集群
redis-cli -a 你的密码 --cluster add-node \
新服务器IP:7007 \
已有节点IP:7001
# 迁移Slot到新节点(平衡数据分布)
redis-cli -a 你的密码 --cluster rebalance \
已有节点IP:7001 \
--cluster-use-empty-masters
# 为新主节点添加从节点
redis-cli -a 你的密码 --cluster add-node \
新服务器IP:7008 \
已有节点IP:7001 \
--cluster-slave \
--cluster-master-id 新主节点的ID六、模拟故障转移测试
<code"># 模拟主节点宕机(停止7001节点) docker stop redis-cluster-redis-7001-1 # 观察故障转移(约5秒) watch -n 1 'redis-cli -a 你的密码 -c -p 7002 cluster nodes | grep master' # 可以看到 7004(原7001的从节点)自动晋升为主节点 # 验证集群仍可读写 redis-cli -a 你的密码 -c -p 7002 get testkey # 正常返回数据 # 重启7001节点 docker start redis-cluster-redis-7001-1 # 7001以从节点身份重新加入(跟随新主7004)
七、总结
Redis Cluster提供自动分片和故障转移双重保障,是Redis从单机走向水平扩展的标准方案。最小三主三从配置可以在6台小规格VPS上运行,成本可控。IDC.Net的香港VPS同账号内网互通,集群节点间通信延迟低至0.1ms,保证槽迁移和主从同步的高效进行。
遇到问题解决不了?
把服务器 IP、报错截图和操作步骤发给我们,工程师 7×24 在线,工单平均 10 分钟内响应。
