温馨提示×

centos如何配置哨兵

小樊
39
2026-08-18 15:54:52
栏目: 智能运维

在 CentOS 上配置 Redis Sentinel(哨兵),通常用于实现 Redis 高可用(主从自动切换)。下面我用 实战步骤 给你一个完整示例,适合生产环境理解和使用。


一、环境说明(示例)

假设你有 3 台 CentOS 服务器:

角色 IP 端口
Redis 主节点 192.168.1.10 6379
Redis 从节点1 192.168.1.11 6379
Redis 从节点2 192.168.1.12 6379
Sentinel 三台都部署 26379

✅ 哨兵推荐 至少 3 个节点,避免脑裂


二、安装 Redis(所有节点)

1️⃣ 安装依赖

yum install -y gcc make

2️⃣ 安装 Redis

cd /usr/local/src
wget https://download.redis.io/redis-stable.tar.gz
tar -zxvf redis-stable.tar.gz
cd redis-stable
make
make install

安装完成后:

redis-server -v

三、配置 Redis 主从

1️⃣ 主节点(192.168.1.10)

/etc/redis/redis.conf

bind 0.0.0.0
protected-mode no
port 6379
daemonize yes
pidfile /var/run/redis.pid
logfile /var/log/redis.log
dir /var/lib/redis

启动:

redis-server /etc/redis/redis.conf

2️⃣ 从节点(192.168.1.11 / 192.168.1.12)

redis.conf

bind 0.0.0.0
protected-mode no
port 6379
daemonize yes
dir /var/lib/redis

slaveof 192.168.1.10 6379

启动:

redis-server /etc/redis/redis.conf

验证:

redis-cli
info replication

四、配置 Sentinel(重点)

1️⃣ 创建哨兵配置文件

三台服务器 上都配置 /etc/redis/sentinel.conf

bind 0.0.0.0
port 26379
daemonize yes
pidfile /var/run/redis-sentinel.pid
logfile /var/log/redis-sentinel.log

sentinel monitor mymaster 192.168.1.10 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 10000
sentinel parallel-syncs mymaster 1

参数说明

参数 说明
mymaster 主节点名称(自定义)
2 至少 2 个哨兵认为主节点宕机才切换
down-after-milliseconds 5 秒无响应认为宕机
failover-timeout 故障转移超时
parallel-syncs 同时同步的从节点数

2️⃣ 启动 Sentinel

redis-sentinel /etc/redis/sentinel.conf

检查:

redis-cli -p 26379
sentinel masters

五、验证高可用

1️⃣ 查看主节点

sentinel get-master-addr-by-name mymaster

2️⃣ 模拟主节点宕机

redis-cli -h 192.168.1.10 shutdown

观察:

  • 哨兵自动选举新主节点
  • 从节点自动切换

六、常见问题

1️⃣ 防火墙

firewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --add-port=26379/tcp --permanent
firewall-cmd --reload

2️⃣ 哨兵数量必须是奇数

✅ 推荐:3 / 5 / 7 个

3️⃣ protected-mode

如果是内网,建议:

protected-mode no

七、生产建议

✅ Redis 主从 + Sentinel
✅ Sentinel 至少 3 台
✅ 客户端连接 Sentinel,而不是 Redis
✅ 使用密码(requirepass + sentinel auth-pass


如果你愿意,我可以:

  • ✅ 给你 带密码的完整配置
  • ✅ 给你 Java / Spring Boot 连接哨兵示例
  • ✅ 帮你画 架构图

你现在用的是 CentOS 7 还是 8?Redis 版本是多少?

0