温馨提示×

centos redis哨兵如何配置

小樊
45
2026-09-08 21:36:35
栏目: 云计算

下面以 CentOS 7/8 为例,说明 Redis Sentinel(哨兵) 的部署与配置步骤。假设你要做 1 主 2 从 + 3 哨兵 的高可用架构。


一、环境准备

1. 服务器规划

角色 IP 端口
Redis 主 192.168.1.10 6379
Redis 从1 192.168.1.11 6379
Redis 从2 192.168.1.12 6379
Sentinel1 192.168.1.10 26379
Sentinel2 192.168.1.11 26379
Sentinel3 192.168.1.12 26379

二、安装 Redis(所有节点)

yum install -y epel-release
yum install -y redis

启动并设置开机自启:

systemctl enable redis
systemctl start redis

三、配置 Redis 主从

1. 主节点(192.168.1.10)

默认即可,确保:

bind 0.0.0.0
protected-mode no

2. 从节点(192.168.1.11 / 12)

编辑 /etc/redis.conf

replicaof 192.168.1.10 6379

重启:

systemctl restart redis

3. 验证主从

redis-cli -h 192.168.1.10 info replication

四、配置 Sentinel(三台都配)

1. 编辑哨兵配置文件

vim /etc/redis-sentinel.conf

基础配置(三台一致,仅 IP 不同):

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 秒无响应认为宕机

2. 启动哨兵

systemctl enable redis-sentinel
systemctl start redis-sentinel

五、验证哨兵

redis-cli -p 26379
> sentinel masters
> sentinel slaves mymaster
> sentinel get-master-addr-by-name mymaster

六、测试故障转移

  1. 停止主节点 Redis:
systemctl stop redis
  1. 查看哨兵日志:
tail -f /var/log/redis/sentinel.log
  1. 哨兵会自动选一个新主,并重新配置从节点。

七、客户端连接建议

客户端应连接 哨兵端口,而非直接连 Redis:

sentinel1:26379
sentinel2:26379
sentinel3:26379

如果你需要:

  • 单机多实例配置
  • Redis 6/7 新版本
  • Docker / Kubernetes 哨兵
  • Java/Spring Boot 连接示例

可以直接告诉我。

0