Redis 集群安装指南
概述
Redis 支持多种集群部署方式,每种方式都有其特定的应用场景和优势。本文将详细介绍主要的集群方式,并提供详细的对比分析。
1. Redis Cluster (官方集群模式)
1.1 特点
- Redis 官方推荐的集群解决方案
- 自动分片,支持水平扩展
- 内置故障转移机制
- 支持 16384 个哈希槽位
- 最小配置 3 主 3 从
1.2 安装配置
步骤1:准备环境
bash
# 安装 Redis
# CentOS/RHEL
yum install redis
# Ubuntu/Debian
apt-get install redis-server
# 或从源码编译
wget http://download.redis.io/redis-stable.tar.gz
tar xzf redis-stable.tar.gz
cd redis-stable
make
步骤2:配置节点
bash
# 创建集群目录
mkdir -p /opt/redis-cluster/{7001,7002,7003,7004,7005,7006}
# 配置每个节点的 redis.conf
# 节点 7001 配置示例
cat > /opt/redis-cluster/7001/redis.conf << EOF
port 7001
cluster-enabled yes
cluster-config-file nodes-7001.conf
cluster-node-timeout 5000
appendonly yes
daemonize yes
pidfile /var/run/redis_7001.pid
logfile /var/log/redis_7001.log
dir /opt/redis-cluster/7001
EOF
步骤3:启动节点
bash
# 启动所有节点
for port in 7001 7002 7003 7004 7005 7006; do
redis-server /opt/redis-cluster/$port/redis.conf
done
步骤4:创建集群
bash
# 使用 redis-cli 创建集群
redis-cli --cluster create \
127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 \
127.0.0.1:7004 127.0.0.1:7005 127.0.0.1:7006 \
--cluster-replicas 1
步骤5:验证集群
bash
# 检查集群状态
redis-cli -p 7001 cluster info
# 查看节点信息
redis-cli -p 7001 cluster nodes
# 测试集群
redis-cli -p 7001 -c set key1 value1
redis-cli -p 7001 -c get key1
2. Redis Sentinel (哨兵模式)
2.1 特点
- 高可用解决方案
- 自动故障检测和转移
- 支持主从复制
- 配置简单,易于管理
- 适合中小规模部署
2.2 安装配置
步骤1:配置主从复制
bash
# 主节点配置 (redis-master.conf)
port 6379
bind 0.0.0.0
appendonly yes
daemonize yes
# 从节点配置 (redis-slave.conf)
port 6380
bind 0.0.0.0
slaveof 127.0.0.1 6379
appendonly yes
daemonize yes
步骤2:配置哨兵
bash
# 哨兵配置文件 (sentinel.conf)
port 26379
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 10000
sentinel parallel-syncs mymaster 1
daemonize yes
logfile /var/log/redis-sentinel.log
步骤3:启动服务
bash
# 启动主节点
redis-server redis-master.conf
# 启动从节点
redis-server redis-slave.conf
# 启动哨兵
redis-sentinel sentinel.conf
步骤4:验证哨兵
bash
# 连接哨兵查看状态
redis-cli -p 26379 sentinel master mymaster
# 查看哨兵信息
redis-cli -p 26379 sentinel sentinels mymaster
3. Redis Proxy (代理模式)
3.1 特点
- 使用代理软件管理集群
- 支持多种代理方案
- 客户端透明访问
- 灵活的负载均衡策略
3.2 使用 Twemproxy (Nutcracker)
安装 Twemproxy
bash
# 安装依赖
yum install autoconf automake libtool
# 下载并编译
git clone https://github.com/twitter/twemproxy.git
cd twemproxy
autoreconf -fvi
./configure --enable-debug=log
make
make install
配置 Twemproxy
yaml
# nutcracker.yml
alpha:
listen: 127.0.0.1:22121
hash: fnv1a_64
distribution: ketama
auto_eject_hosts: true
redis: true
server_retry_timeout: 2000
server_failure_limit: 1
servers:
- 127.0.0.1:6379:1
- 127.0.0.1:6380:1
- 127.0.0.1:6381:1
启动 Twemproxy
bash
nutcracker -c nutcracker.yml -d
3.3 使用 Codis
安装 Codis
bash
# 下载 Codis
wget https://github.com/CodisLabs/codis/releases/download/3.2.2/codis3.2.2-go1.9.2-linux.tar.gz
tar -xzf codis3.2.2-go1.9.2-linux.tar.gz
cd codis3.2.2-go1.9.2-linux
配置 Codis
bash
# 创建配置文件
cat > config.ini << EOF
coordinator_name=zookeeper
coordinator_addr=127.0.0.1:2181
product_name=codis-demo
product_auth=
EOF
# 启动 Codis Dashboard
./codis-dashboard --config=config.ini --log=stdout
# 启动 Codis Proxy
./codis-proxy --config=config.ini --log=stdout
4. Redis Enterprise (企业版)
4.1 特点
- Redis 官方企业级解决方案
- 自动分片和故障转移
- 多租户支持
- 企业级监控和管理
- 支持多种数据结构和模块
4.2 安装配置
下载 Redis Enterprise
bash
# 下载 Redis Enterprise
wget https://download.redislabs.com/redis-enterprise/redis-enterprise-server-6.2.0-1.el7.x86_64.rpm
rpm -i redis-enterprise-server-6.2.0-1.el7.x86_64.rpm
配置集群
bash
# 初始化节点
/opt/redislabs/bin/rlcheck
# 创建集群
/opt/redislabs/bin/rladmin cluster create name cluster1
# 创建数据库
/opt/redislabs/bin/rladmin database create name db1 memory_size 1gb
5. 集群方式对比分析
5.1 功能特性对比
| 特性 | Redis Cluster | Redis Sentinel | Twemproxy | Codis | Redis Enterprise |
|---|---|---|---|---|---|
| 分片支持 | ✅ 自动分片 | ❌ 无分片 | ✅ 代理分片 | ✅ 代理分片 | ✅ 自动分片 |
| 故障转移 | ✅ 内置 | ✅ 内置 | ❌ 无 | ✅ 支持 | ✅ 内置 |
| 水平扩展 | ✅ 支持 | ❌ 不支持 | ✅ 支持 | ✅ 支持 | ✅ 支持 |
| 客户端兼容 | ⚠️ 需要集群客户端 | ✅ 标准客户端 | ✅ 标准客户端 | ✅ 标准客户端 | ✅ 标准客户端 |
| 配置复杂度 | 中等 | 简单 | 简单 | 复杂 | 简单 |
| 运维成本 | 中等 | 低 | 中等 | 高 | 低 |
5.2 性能对比
| 指标 | Redis Cluster | Redis Sentinel | Twemproxy | Codis | Redis Enterprise |
|---|---|---|---|---|---|
| 吞吐量 | 高 | 中等 | 高 | 高 | 最高 |
| 延迟 | 低 | 低 | 中等 | 中等 | 最低 |
| 内存效率 | 高 | 高 | 中等 | 中等 | 高 |
| 网络开销 | 低 | 低 | 中等 | 中等 | 低 |
5.3 适用场景对比
| 场景 | Redis Cluster | Redis Sentinel | Twemproxy | Codis | Redis Enterprise |
|---|---|---|---|---|---|
| 小规模应用 | ❌ 过度设计 | ✅ 适合 | ✅ 适合 | ❌ 复杂 | ❌ 成本高 |
| 中等规模应用 | ✅ 适合 | ✅ 适合 | ✅ 适合 | ✅ 适合 | ✅ 适合 |
| 大规模应用 | ✅ 适合 | ❌ 不支持 | ✅ 适合 | ✅ 适合 | ✅ 最适合 |
| 高可用要求 | ✅ 适合 | ✅ 适合 | ❌ 不支持 | ✅ 适合 | ✅ 最适合 |
| 数据分片需求 | ✅ 适合 | ❌ 不支持 | ✅ 适合 | ✅ 适合 | ✅ 适合 |
| 企业级需求 | ⚠️ 基础功能 | ❌ 功能有限 | ❌ 功能有限 | ⚠️ 部分支持 | ✅ 最适合 |
5.4 成本对比
| 成本类型 | Redis Cluster | Redis Sentinel | Twemproxy | Codis | Redis Enterprise |
|---|---|---|---|---|---|
| 软件成本 | 免费 | 免费 | 免费 | 免费 | 付费 |
| 硬件成本 | 中等 | 低 | 中等 | 中等 | 低 |
| 运维成本 | 中等 | 低 | 中等 | 高 | 低 |
| 学习成本 | 中等 | 低 | 低 | 高 | 低 |
6. 选择建议
6.1 按规模选择
- 小规模 (1-10GB):Redis Sentinel
- 中等规模 (10-100GB):Redis Cluster 或 Twemproxy
- 大规模 (100GB+):Redis Cluster 或 Redis Enterprise
6.2 按需求选择
- 高可用优先:Redis Sentinel 或 Redis Enterprise
- 分片扩展优先:Redis Cluster 或 Codis
- 简单运维优先:Redis Sentinel 或 Redis Enterprise
- 成本优先:Redis Cluster 或 Twemproxy
6.3 按技术栈选择
- 已有 ZooKeeper:考虑 Codis
- 无特殊依赖:Redis Cluster 或 Redis Sentinel
- 企业环境:Redis Enterprise
7. 最佳实践
7.1 集群规划
- 使用奇数个节点(3、5、7等)
- 节点间网络延迟应小于 1ms
- 确保足够的磁盘空间和内存
7.2 监控配置
bash
# 使用 Redis Exporter 监控
docker run -d --name redis-exporter \
-p 9121:9121 \
oliver006/redis_exporter \
--redis.addr=redis://localhost:6379
7.3 备份策略
bash
# 定期备份
redis-cli --rdb /backup/redis-$(date +%Y%m%d).rdb
# 使用 Redis AOF
# 在 redis.conf 中启用
appendonly yes
appendfsync everysec
总结
选择合适的 Redis 集群方式需要综合考虑:
- 业务规模:数据量和访问量
- 可用性要求:故障恢复时间要求
- 扩展性需求:未来增长预期
- 运维能力:团队技术水平
- 成本预算:硬件和软件成本
对于大多数场景,Redis Cluster 是最佳选择,它提供了良好的平衡性。对于企业级应用,Redis Enterprise 提供了最完整的功能和最低的运维成本。
Redis Cluster(3主3从)
docker-compose.yml 示例(Redis Cluster 3主3从)
yaml
version: "3.9"
services:
redis1:
image: redis:7.2.3
container_name: redis1
command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
volumes:
- ./conf/redis1.conf:/usr/local/etc/redis/redis.conf
ports:
- "6371:6379"
- "16371:16379" # cluster bus port (服务端口+10000)
networks:
redis-cluster:
ipv4_address: 172.30.0.11
redis2:
image: redis:7.2.3
container_name: redis2
command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
volumes:
- ./conf/redis2.conf:/usr/local/etc/redis/redis.conf
ports:
- "6372:6379"
- "16372:16379"
networks:
redis-cluster:
ipv4_address: 172.30.0.12
redis3:
image: redis:7.2.3
container_name: redis3
command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
volumes:
- ./conf/redis3.conf:/usr/local/etc/redis/redis.conf
ports:
- "6373:6379"
- "16373:16379"
networks:
redis-cluster:
ipv4_address: 172.30.0.13
redis4:
image: redis:7.2.3
container_name: redis4
command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
volumes:
- ./conf/redis4.conf:/usr/local/etc/redis/redis.conf
ports:
- "6374:6379"
- "16374:16379"
networks:
redis-cluster:
ipv4_address: 172.30.0.14
redis5:
image: redis:7.2.3
container_name: redis5
command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
volumes:
- ./conf/redis5.conf:/usr/local/etc/redis/redis.conf
ports:
- "6375:6379"
- "16375:16379"
networks:
redis-cluster:
ipv4_address: 172.30.0.15
redis6:
image: redis:7.2.3
container_name: redis6
command: ["redis-server", "/usr/local/etc/redis/redis.conf"]
volumes:
- ./conf/redis6.conf:/usr/local/etc/redis/redis.conf
ports:
- "6376:6379"
- "16376:16379"
networks:
redis-cluster:
ipv4_address: 172.30.0.16
networks:
redis-cluster:
driver: bridge
ipam:
config:
- subnet: 172.30.0.0/16
Redis 配置文件(每个节点都相同)
在 ./conf/redis1.conf ~ ./conf/redis6.conf 写入以下内容:
conf
port 6379
cluster-enabled yes
cluster-config-file nodes.conf
cluster-node-timeout 5000
appendonly yes
protected-mode no
bind 0.0.0.0
端口用 docker-compose.yml 里的映射,不需要在配置里修改。
cluster-config-file 会在运行时自动生成。
启动集群
-
- 启动容器:
bash
docker-compose up -d
-
- 初始化 Redis Cluster(3主3从):
bash
docker exec -it redis1 redis-cli --cluster create \
172.30.0.11:6379 \
172.30.0.12:6379 \
172.30.0.13:6379 \
172.30.0.14:6379 \
172.30.0.15:6379 \
172.30.0.16:6379 \
--cluster-replicas 1
--cluster-replicas 1 表示给每个主节点分配一个从节点。
最终结果:3 主(redis1-redis3)+ 3 从(redis4-redis6)。
-
- 查看集群状态:
bash
docker exec -it redis1 redis-cli cluster nodes
2cab15ef60892339998cfb5471884a603349edd6 172.30.0.16:6379@16379 slave a62209c24fca890321cd07bb961429a69ccf1eb8 0 1757037784577 2 connected
a62209c24fca890321cd07bb961429a69ccf1eb8 172.30.0.12:6379@16379 master - 0 1757037783674 2 connected 5461-10922
86ba948e1819a3460d96e3b637806a7b1ef0d60d 172.30.0.15:6379@16379 slave 925ee5e890ebdd43267376ef816a4973b66850ea 0 1757037784176 1 connected
925ee5e890ebdd43267376ef816a4973b66850ea 172.30.0.11:6379@16379 myself,master - 0 1757037782000 1 connected 0-5460
d078bbe5fcf98e034f91cb32eb50be7939eaa1a1 172.30.0.13:6379@16379 master - 0 1757037783173 3 connected 10923-16383
391399d2a2bfec329be09659c2e7b9e4c7b245a7 172.30.0.14:6379@16379 slave d078bbe5fcf98e034f91cb32eb50be7939eaa1a1 0 1757037783000 3 connected
其他常用命令
bash
# 查看集群信息
docker exec -it redis1 redis-cli cluster info
# 更直观的槽位分布
docker exec -it redis1 redis-cli cluster slots
📘 Redis Cluster 跨物理机扩展操作手册
跨物理机扩展 Redis Cluster 操作手册 。假设你已经有一个 3 主 3 从的集群,现在要在一台新的物理机上加入新的节点(可以是主节点或从节点)。
一、前提条件
-
网络连通性
-
集群所有机器必须能互相访问:
- 服务端口:
6379 - 集群通信端口:
16379(服务端口 + 10000)
- 服务端口:
-
如果有防火墙 / 安全组,必须放行这两个端口。
-
-
Redis 配置文件准备
在新机器(假设 IP 是
192.168.20.50)的redis.conf:confport 6379 cluster-enabled yes cluster-config-file nodes.conf cluster-node-timeout 5000 appendonly yes protected-mode no bind 0.0.0.0 # 确保集群通信用的是正确的内网 IP cluster-announce-ip 192.168.20.50 cluster-announce-port 6379 cluster-announce-bus-port 16379 -
启动 Redis
bashredis-server /etc/redis/redis.conf
二、作为 主节点 加入
-
执行命令把新节点加入集群:
bashredis-cli --cluster add-node 192.168.20.50:6379 192.168.30.11:6379192.168.20.50:6379→ 新节点192.168.30.11:6379→ 集群中任意已存在的节点
-
重新平衡槽位(把一部分 slot 分给新主机):
bashredis-cli --cluster rebalance 192.168.30.11:6379这会自动把 16384 槽位的一部分迁移到新节点。
三、作为 从节点 加入
-
查找主节点 ID
在现有集群中执行:
bashredis-cli -h 192.168.30.11 -p 6379 cluster nodes输出类似:
07c37dfe... 192.168.30.11:6379@16379 master - 0 1693900000 1 connected 0-5460 f0c37aae... 192.168.30.12:6379@16379 master - 0 1693900000 2 connected 5461-10922记录你想挂载的主节点 ID,例如
07c37dfe...。 -
把新节点作为从节点加入:
bashredis-cli --cluster add-node 192.168.20.50:6379 192.168.30.11:6379 \ --cluster-slave --cluster-master-id 07c37dfe...
四、验证集群状态
-
查看集群节点分布:
bashredis-cli -h 192.168.30.11 -p 6379 cluster nodes -
查看槽位情况:
bashredis-cli -h 192.168.30.11 -p 6379 cluster slots -
查看集群整体状态:
bashredis-cli -h 192.168.30.11 -p 6379 cluster info
确认:
- 新节点是否出现在
cluster nodes列表里。 - 如果是主节点,是否分到槽位。
- 如果是从节点,是否跟随某个主节点。
五、常见问题排查
-
新节点一直报
127.0.0.1,导致其他机器连不上-
检查
redis.conf是否配置了:confcluster-announce-ip <本机内网IP> -
重启 Redis 后再加入集群。
-
-
槽位迁移慢或失败
-
执行
redis-cli --cluster rebalance时可加参数:bashredis-cli --cluster rebalance 192.168.30.11:6379 --cluster-use-empty-masters -
适合新增空节点时强制迁移槽位。
-
-
防火墙未放行
- 必须放行
6379和16379,否则节点间无法握手。
- 必须放行
✅ 到这里,你就可以把 新的物理机节点平滑加入 Redis Cluster,不论它是主节点还是从节点。
在 Windows 上让 Redis(安装目录 D:\tools\Redis-x64-5.0.14.1) 注册为系统服务,并设置为 开机自启动。
下面我一步步教你怎么做 👇
✅ 一、确认 redis-server.exe 路径
请确保文件存在:
D:\tools\Redis-x64-5.0.14.1\redis-server.exe
✅ 二、以管理员身份打开 PowerShell 或 CMD
(必须是管理员模式,否则注册服务会失败)
✅ 三、注册 Redis 服务
执行以下命令:
cmd
"D:\tools\Redis-x64-5.0.14.1\redis-server.exe" --service-install "D:\tools\Redis-x64-5.0.14.1\redis.windows.conf" --loglevel verbose
参数说明:
--service-install:将 Redis 注册为 Windows 服务。"D:\tools\Redis-x64-5.0.14.1\redis.windows.conf":Redis 配置文件路径。
(如果没有,可以用redis.conf或自己复制一个配置文件)--loglevel verbose:日志详细等级,可选。
✅ 四、启动服务
注册成功后执行:
cmd
"D:\tools\Redis-x64-5.0.14.1\redis-server.exe" --service-start
✅ 五、设置服务为开机自启动
运行以下命令(只需执行一次):
cmd
sc config Redis start= auto
⚠️ 注意:
start=后面必须有一个空格!
✅ 六、验证状态
查看 Redis 服务是否安装成功:
cmd
sc query Redis
输出示例:
SERVICE_NAME: Redis
TYPE : 10 WIN32_OWN_PROCESS
STATE : 4 RUNNING
START_TYPE : 2 AUTO_START
表示服务已启动并设置为开机自动启动 ✅
✅ 七、常用管理命令
| 操作 | 命令 |
|---|---|
| 启动服务 | net start Redis |
| 停止服务 | net stop Redis |
| 删除服务 | "D:\tools\Redis-x64-5.0.14.1\redis-server.exe" --service-uninstall |
✅ 八、可选:验证 Redis 是否可用
执行:
cmd
"D:\tools\Redis-x64-5.0.14.1\redis-cli.exe" ping
如果返回:
PONG
说明 Redis 已经启动成功 🎉
Redis 清理脚本 由系统定时任务自动触发(例如每 10 分钟执行一次),我们来优化脚本,使其完全自动化、无窗口执行、兼容任务计划程序。
✅ 九、Windows Redis services
bash
cd /d D:\tools\Redis-x64-5.0.14.1
redis-server.exe --service-install redis.windows.conf --loglevel verbose
# 如果你没有 redis.windows.conf 文件,可以用默认的: redis-server.exe --service-install
# 启动服务
redis-server.exe --service-start
# 验证是否成功
sc query redis
# 停止&启动服务
net stop Redis
net start Redis
✅ 清理Redis存储空间脚本:C:\tools\redis_clean.ps1
powershell
# redis_clean.ps1
# -----------------------------
# 功能:自动检测 Redis 键数量,超出阈值则清理
# 可被 Windows 任务计划程序定时触发
# -----------------------------
# === Configuration ===
$redisHost = "127.0.0.1"
$redisPort = 6379
$redisPassword = "foobared" # <<< Set your Redis password
$redisCliPath = "D:\tools\Redis-x64-5.0.14.1\redis-cli.exe" # Path to redis-cli
$threshold = 100
$logFile = "D:\bat\redis_clean.log"
# === Execution ===
try {
# Check if redis-cli exists
if (!(Test-Path $redisCliPath)) {
$msg = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ❌ redis-cli not found: $redisCliPath"
Add-Content -Path $logFile -Value $msg
exit 1
}
# Get the number of keys in Redis
# $dbsizeOutput = & "$redisCliPath" -h $redisHost -p $redisPort -a $redisPassword dbsize 2>$null
# $dbsize = [int]($dbsizeOutput -replace "\D", "")
$totalKeys = 0
for ($i = 0; $i -lt 16; $i++) {
$output = & "$redisCliPath" -h $redisHost -p $redisPort -a $redisPassword -n $i dbsize 2>$null
$keys = [int]($output -replace "\D", "")
$totalKeys += $keys
}
$dbsize = $totalKeys
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
if ($dbsize -gt $threshold) {
# Exceeds threshold, perform cleanup
& "$redisCliPath" -h $redisHost -p $redisPort -a $redisPassword flushdb | Out-Null
$msg = "$time [Cleanup Executed] dbsize=$dbsize > $threshold, FLUSHDB executed"
} else {
$msg = "$time [Normal] dbsize=$dbsize <= $threshold, no cleanup needed"
}
# Write to log
Add-Content -Path $logFile -Value $msg
} catch {
$err = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ❌ Execution error: $($_.Exception.Message)"
Add-Content -Path $logFile -Value $err
}
✅ 创建任务计划(自动执行脚本)
在 PowerShell(管理员模式)执行以下命令:
powershell
schtasks /create /tn "RedisAutoClean" `
/tr "powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File C:\tools\redis_clean.ps1" `
/sc minute /mo 10 /ru "SYSTEM" /f
- 参数说明:
/tn "RedisAutoClean":任务名称/tr:任务执行的命令(PowerShell 脚本)/sc minute /mo 10:每 10 分钟执行一次/ru "SYSTEM":使用系统账户运行,无需登录用户-WindowStyle Hidden:不弹出窗口/f:覆盖已有任务
✅ 查看任务运行情况
查看任务是否创建成功:
powershell
schtasks /query /tn "RedisAutoClean"
手动运行测试:
powershell
schtasks /run /tn "RedisAutoClean"
查看日志:
powershell
type C:\tools\redis_clean.log
✅ 日志示例
2025-10-09 09:00:00 [正常] dbsize=182340 <= 300000,无需清理
2025-10-09 09:10:00 [清理执行] dbsize=321504 > 300000,已执行 FLUSHDB
✅ 可选增强功能
如果你只想清理特定前缀(比如 session:*),可以把清理命令改成:
powershell
& "$redisCliPath" -h $redisHost -p $redisPort --scan --pattern "session:*" |
ForEach-Object { & "$redisCliPath" -h $redisHost -p $redisPort del $_ } | Out-Null
$msg = "$time [清理执行] dbsize=$dbsize > $threshold,已清理前缀 session:* 的键"