Redis 哨兵模式搭建指南(Windows + WSL2 环境 · 简洁版)

76 阅读2分钟

Redis 哨兵模式搭建指南(Windows + WSL2 环境 · 简洁版)

适用于 Ubuntu 24.04 (WSL2),5 分钟快速搭建高可用 Redis 哨兵集群(1 主 + 2 从 + 3 哨兵)。


✅ 一、准备工作

1. 使用 WSL2(推荐)

在 Windows PowerShell 中启用 WSL2:

wsl --install

重启后安装 Ubuntu 24.04。

2. 换源加速(可选但推荐)

sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo sed -i 's|http://[a-z0-9\.]*\.archive\.ubuntu\.com|https://mirrors.aliyun.com|g' /etc/apt/sources.list
sudo sed -i 's|http://security\.ubuntu\.com|https://mirrors.aliyun.com|g' /etc/apt/sources.list
sudo apt update

3. 安装 Redis 完整套件

sudo apt install redis -y
# 验证
redis-server --version   # 应 ≥ 7.2
redis-sentinel --version

📁 二、创建目录结构

mkdir -p ~/redis-sentinel/{master,slave1,slave2,sentinel1,sentinel2,sentinel3,logs}
cd ~/redis-sentinel

📄 三、配置文件

1. 主节点 master/redis.conf

port 6380
bind 0.0.0.0
protected-mode no
daemonize no
dir ./master

2. 从节点 slave1/redis.confslave2 同理,改端口为 6382)

port 6381
bind 0.0.0.0
protected-mode no
daemonize no
dir ./slave1
replicaof 127.0.0.1 6380

3. 哨兵 sentinel1/sentinel.confsentinel2/3 改端口为 26381/26382)

port 26380
bind 0.0.0.0
protected-mode no
daemonize no
dir ./sentinel1
sentinel monitor mymaster 127.0.0.1 6380 2
sentinel down-after-milliseconds mymaster 5000

⚠️ 所有 .conf 文件中必须包含 daemonize no


▶️ 四、启动集群(后台运行)

# 启动主从
nohup redis-server master/redis.conf > logs/master.log 2>&1 &
nohup redis-server slave1/redis.conf > logs/slave1.log 2>&1 &
nohup redis-server slave2/redis.conf > logs/slave2.log 2>&1 &

# 等待 3 秒建立主从
sleep 3

# 启动哨兵
nohup redis-sentinel sentinel1/sentinel.conf > logs/sentinel1.log 2>&1 &
nohup redis-sentinel sentinel2/sentinel.conf > logs/sentinel2.log 2>&1 &
nohup redis-sentinel sentinel3/sentinel.conf > logs/sentinel3.log 2>&1 &

🔍 五、验证

查看主从状态

redis-cli -p 6380 info replication
# 应显示 role:master, connected_slaves:2

查看哨兵状态

redis-cli -p 26380 sentinel masters
# 应显示 num-slaves:2, num-other-sentinels:2

获取当前主节点地址(应用连接用)

redis-cli -p 26380 sentinel get-master-addr-by-name mymaster

🧪 六、测试故障转移

  1. 杀掉主节点:
    pkill -f "redis-server.*6380"
    
  2. 等待 5~10 秒,查看日志:
    tail -f logs/sentinel1.log
    # 应出现 +switch-master 日志
    
  3. 查询新主节点:
    redis-cli -p 26380 sentinel get-master-addr-by-name mymaster
    # 端口应变为 6381 或 6382
    

🧹 七、停止所有进程

pkill -f redis-server
pkill -f redis-sentinel

💡 关键说明

  • 至少 3 个哨兵:避免脑裂,实现多数派决策。
  • 应用连接方式:不要直连 Redis,应通过 Sentinel 获取主节点地址。
  • 日志位置:所有日志在 ~/redis-sentinel/logs/ 下,出错时优先查看。
  • 生产环境:务必设置密码(requirepass + sentinel auth-pass)。

✅ 完成!你现在拥有一个本地高可用 Redis 哨兵集群。

文档基于 Ubuntu 24.04 + Redis 7.2 编写,兼容 WSL2。