下面以 CentOS 7/8 为例,介绍 Redis 主从(Master-Slave) 的配置方式,适用于 Redis 5/6/7。
| 角色 | IP | 端口 |
|---|---|---|
| Master | 192.168.1.10 | 6379 |
| Slave | 192.168.1.11 | 6379 |
# CentOS 7/8
yum install -y epel-release
yum install -y redis
启动并开机自启:
systemctl enable redis
systemctl start redis
编辑配置文件:
vi /etc/redis.conf
关键配置:
bind 0.0.0.0
protected-mode no
port 6379
daemonize yes
(如有密码)
requirepass 123456
重启:
systemctl restart redis
编辑从节点配置:
vi /etc/redis.conf
核心配置:
bind 0.0.0.0
port 6379
replicaof 192.168.1.10 6379
如果 Master 有密码:
masterauth 123456
重启:
systemctl restart redis
在 Slave 上执行:
redis-cli
info replication
应看到:
role:slave
master_host:192.168.1.10
master_link_status:up
在 Master 上:
redis-cli
info replication
应看到:
role:master
connected_slaves:1
Master:
redis-cli -a 123456 set test hello
Slave:
redis-cli get test
返回 hello 即成功。
firewall-cmd --add-port=6379/tcp --permanent
firewall-cmd --reload
从节点默认只读:
replica-read-only yes
Redis 7 中:
slaveof → replicaofslave → replica多个 Slave 只需都配置:
replicaof 192.168.1.10 6379
如果你需要 哨兵(Sentinel) 或 Cluster 集群 配置,也可以告诉我。