MySQL, Oracle, Linux, 软件架构及大数据技术知识分享平台

网站首页 > 精选文章 / 正文

从0到1:基于 Linux 快速搭建高可用 Redis Sentinel 集群(实战指南)

2025-04-26 18:44 huorong 精选文章 1 ℃ 0 评论


前言

在生产环境中,为了保障 Redis 服务的高可用,通常会使用 Redis Sentinel 进行故障监测与自动主从切换。本文将手把手带你在 Linux 系统上快速搭建一个高可用的 Redis Sentinel 集群,适用于中小型生产环境或测试环境部署。





1. 环境准备


  • 系统版本:CentOS 7 / Ubuntu 20.04
  • Redis 版本:6.0 及以上
  • 节点规划:

    • Redis Master:192.168.10.10
    • Redis Slave1:192.168.10.11
    • Redis Slave2:192.168.10.12
    • Sentinel1:192.168.10.10
    • Sentinel2:192.168.10.11
    • Sentinel3:192.168.10.12






2. 安装 Redis



在每台服务器上安装 Redis:

# 安装依赖

sudo yum install -y gcc jemalloc jemalloc-devel


# 下载并编译 Redis

cd /usr/local/src

wget http://download.redis.io/releases/redis-6.2.6.tar.gz

tar xzf redis-6.2.6.tar.gz

cd redis-6.2.6

make

make install PREFIX=/usr/local/redis

配置环境变量:

echo 'export PATH=/usr/local/redis/bin:$PATH' >> /etc/profile

source /etc/profile

验证安装:

redis-server -v






3. 配置 Redis Master 和 Slave




3.1 配置 Master



编辑
/usr/local/redis/redis.conf:

bind 0.0.0.0

port 6379

daemonize yes

protected-mode no

启动 Master:

redis-server /usr/local/redis/redis.conf


3.2 配置 Slave



在 192.168.10.11 和 192.168.10.12 上编辑 redis.conf:

bind 0.0.0.0

port 6379

daemonize yes

protected-mode no

replicaof 192.168.10.10 6379

启动 Slave:

redis-server /usr/local/redis/redis.conf

验证主从同步:

redis-cli -h 192.168.10.11 info replication

输出中 role:slave 表示配置成功。





4. 配置 Redis Sentinel




4.1 创建 Sentinel 配置文件



每台机器新建
/usr/local/redis/sentinel.conf:

port 26379

daemonize yes

protected-mode no

dir "/tmp"

sentinel monitor mymaster 192.168.10.10 6379 2

sentinel down-after-milliseconds mymaster 5000

sentinel failover-timeout mymaster 10000

sentinel parallel-syncs mymaster 1

解释:


  • mymaster:监控的主节点名称。
  • 2:至少有2个 Sentinel 认定主节点故障才触发故障转移。




4.2 启动 Sentinel


redis-sentinel /usr/local/redis/sentinel.conf

用以下命令查看 Sentinel 状态:

redis-cli -p 26379 info Sentinel






5. 模拟故障测试



关闭 Master Redis:

pkill redis-server

观察 Sentinel 日志,可以看到:

+sdown master mymaster 192.168.10.10 6379

+new-epoch 1

+try-failover master mymaster 192.168.10.10 6379

+failover-state-select-slave master mymaster 192.168.10.10 6379

...

+switch-master mymaster 192.168.10.10 6379 192.168.10.11 6379

说明 Sentinel 成功选举了新的 Master。




6. 总结

通过本文实操,我们在 Linux 上成功搭建了一个高可用的 Redis Sentinel 集群,并完成了主从切换测试。

在实际生产中,可以结合 Keepalived + VIP 技术,让客户端无需感知主从 IP 变化,从而进一步提升系统稳定性。



后续可以拓展内容:


  • 使用 Supervisor 守护 Redis 和 Sentinel 进程
  • 配置持久化(RDB + AOF)
  • 配合 Prometheus + Grafana 进行监控

Tags:linux 安装redis

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言