Redis三主三从高可用集群部署全过程详解
1. 环境规划
准备3 台服务器,每台部署两个 Redis 实例:
|
|
|
|
---|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
每个 Redis 实例运行在不同的端口上。
2. 配置 Redis 实例
2.1 在每台主机上安装 Redis
下载源码包
下载地址:
https://redis.io/downloads/
也可以在有网环境直接获取
wget https://download.redis.io/releases/redis-7.0.15.tar.gz

解压并编译
# 解压到/data目录下
tar -xvf redis-7.0.15.tar.gz -C /opt
# 编译
[root@redis01 ~]# cd /opt
[root@redis01 opt]# cd redis-7.0.15/
[root@redis01 redis-7.0.15]# make
编译完成后,二进制文件会生成在 src 目录下:
-
redis-server:Redis 服务端 -
redis-cli:Redis 客户端
分发到其他主机
将编译好的 Redis 文件夹复制到其他两台主机:
scp -rp /opt/redis-7.0.15/ root@10.0.0.42:/opt
scp -rp /opt/redis-7.0.15/ root@10.0.0.43:/opt
2.2 配置 Redis 实例
在每台主机上运行两个 Redis 实例,需要为每个实例创建独立的配置文件和数据目录。以主机 1 为例:
创建配置文件存放路径
mkdir -p /opt/redis/{6379,6380}/{conf,data,logs,pid}
master1-6379配置文件
cat > /opt/redis/6379/conf/redis_6379.conf <<EOF
bind 0.0.0.0
protected-mode no
port 6379
daemonize yes
logfile /opt/redis/6379/logs/redis_6379.log
pidfile /opt/redis/6379/pid/redis_6379.pid
dbfilename "redis_6379.rdb"
dir /opt/redis/6379/data
cluster-enabled yes
cluster-config-file node_6379.conf
cluster-node-timeout 15000
EOF
slave-7380配置文件
cat > /opt/redis/6380/conf/redis_6380.conf << EOF
bind 0.0.0.0
protected-mode no
# 指定 Redis 监听的 TCP 端口,默认
port 6380
daemonize yes
logfile /opt/redis/6380/logs/redis_6380.log
pidfile /opt/redis/6380/pid/redis_6380.pid
dbfilename "redis_6380.rdb"
dir /opt/redis/6380/data
cluster-enabled yes
cluster-config-file node_6380.conf
cluster-node-timeout 15000
EOF
配置文件常用字段
-
bind:指定 Redis 服务绑定的 IP 地址,默认127.0.0.1(仅本机访问) -
protected-mode:是否启用保护模式,默认为yes,Redis 在未设置密码且非本地访问时,自动拒绝连接 -
port:指定redis监听的TCP端口,默认6379 -
daemonize:指定redis是否以后台守护进程模式运行,默认为no -
logfile:指定日志输出文件路径 -
pidfile:pid文件存放位置 -
dir:数据文件目录,Redis 将持久化文件(如 RDB 文件和 AOF 文件)存储在此目录 -
cluster-enabled:启用 Redis 集群模式,默认为no -
cluster-config-file:指定 Redis 集群节点的配置文件 -
cluster-node-timeout:Redis 集群中节点之间通信的超时时间,默认15000 毫秒
配置环境变量
vi /etc/profile
export PATH=$PATH:/opt/redis-7.0.15/src
source /etc/profile
启动redis
# 启动6379
redis-server /opt/redis/6379/conf/redis_6379.conf
# 启动7380
redis-server /opt/redis/6380/conf/redis_6380.conf
# 停止
redis-cli -c -h 10.0.0.41 -p 6379 shutdown
redis-cli -c -h 10.0.0.41 -p 6380 shutdown
配置主机 2 和主机 3
重复上述步骤,将每个节点的redis都启动起来 查看结果:
ps -ef |grep redis
redis-server --version
每个节点都运行两个redis

3. 创建 Redis 集群
3.1 启用集群模式
在所有节点启动完成后,可以通过 redis-cli 创建集群。任选一台主机,执行以下命令:
redis-cli --cluster create \
10.0.0.41:6379 10.0.0.42:6379 10.0.0.43:6379 \
10.0.0.41:6380 10.0.0.42:6380 10.0.0.43:6380 \
--cluster-replicas 1
-
--cluster-replicas 1 表示每个主节点有一个从节点。
【温馨提示】每个节点需要关闭防火墙或开通对应的实例端口
输入yes,接受
创建完成后,Redis 会自动分配主从角色
3.2 验证集群状态
通过以下命令查看集群状态:
redis-cli -p 6379 cluster nodes
你应该看到输出类似以下内容:

至此,集群已经部署完成!
THE END