一、本文目的
Redis的主从配置分为两篇文章,第一篇主要介绍了Redis主从配置的搭建过程及使用,第二篇主要说明各种情况下Redis主从状态,如Master挂掉,Slaver挂掉,挂掉后重新加入等。
二、常用命令
- 根据配置文件启动redis: src/redis-server redis.confg
- 启动redis客户端:redis-cli -p port
- Slaver连接Master:slaveof host:ip (测试时使用slaveof手动连接master,正式环境使用配置文件)
- 关闭Redis:shutdown
- 查看主从信息:info Replication
三、Redis的配置
1、按照1主2从的结构搭建,即1个Master,2个Slaver节点
2、Redis配置文件redis.conf的配置
daemonize (后台运行) | pidfile | port | logfile(日志,src目录) | # slaveof <masterip> <masterport> (测试时使用slaveof手动连接master,正式环境使用配置文件) | |
Master | yes | /var/run/redis6379.pid | 6379 | "redis6379.log" | |
Slaver1 | yes | /var/run/redis6381.pid | 6381 | "redis6381.log" | slaveof 127.0.0.1 6379 |
Slaver2 | yes | /var/run/redis6382.pid | 6382 | "redis6382.log" | slaveof 127.0.0.1 6379 |
3、配置完成后3个节点都是Master

4、配置主从节点(通过info replication查看主从关系)

5、Master节点设置key后异步同步到Slaver节点;Slaver节点只能读取数据,不能修改

6、主节点挂掉后,手动将S1子节点升级为Master(命令:slaveof no one 手动将Slaver节点升级为Master节点)
操作步骤如下:
a) Master节点:Shutdown关闭节点
b) Slaver1节点:slaveof no one将其升级为Master节点
c) Slaver2节点:使用slaveof 127.0.0.1 6381 重连Slaver2将其视为Master节点
d) 原来的Master节点:重新启动后,可以使用slaveof 127.0.0.1 6381 连接Slaver2将其视为Master节点,自己成为Slaver节点

7、使用哨兵模式,自动监视Master节点,当前挂掉后,自动将Slaver节点变为Master节点
a) sentinel.conf配置文件,修改sentinel monitor host6379 127.0.0.1 6379 1,其它使用默认即可
host6379 主机名称,随便起 主机IP 端口 1表示选举,某个slaver得到超过1票则成成为Master节点
host6379 主机名称,随便起 主机IP 端口 1表示选举,某个slaver得到超过1票则成成为Master节点
b) 启动sentinel: ./redis-sentinel ../sentinel.conf


8、手动shutdown Master节点后,等待一段时间(大概一分钟),sentinel会重新选举Master节点。下面将6381选举为Master节点,6382自动重连6381的Master节点

6379 原来的Master节点重启后变成Slaver节点

四、总结
- Master可读可写,Slaver只能读,不能写
- Master可以对应多个Slaver,但是数量越多压力越大,延迟就可能越严重
- Master写入后立即返回,几乎同时将写入异步同步到各个Slaver,所以基本上延迟可以忽略
- 可以通过slaveof no one命令将Slaver升级为Master(当Master挂掉时,手动将某个Slaver变为Master)
- 可以通过sentinel哨兵模式监控Master,当Master挂掉时自动选举Slaver变为Master,其它Slaver自动重连新的Master