Redis作为一个高性能、高可用的分布式缓存数据库,提供了主从复制的能力。被复制的节点成为主(master)节点,复制的节点称为从(slave)节点。
Redis主从复制除了保障服务的稳定性之外,还可以做读写分离,进行扩容,关于Redis集群节点的拆分可以按照AKF原则来拆分,这在后面的实战部分会进行详细描述,这一部分主要分析Redis主从复制的过程及实现细节。
开启功能
Redis主从复制可以通过配置文件配置,也可以通过客户端发送命令来触发,一旦服务器节点作为从节点开始复制,就无法再写入数据。
# Master-Replica replication. Use replicaof to make a Redis instance a copy of
# another Redis server. A few things to understand ASAP about Redis replication.
#
# +------------------+ +---------------+
# | Master | ---> | Replica |
# | (receive writes) | | (exact copy) |
# +------------------+ +---------------+
#
# 1) Redis replication is asynchronous, but you can configure a master to
# stop accepting writes if it appears to be not connected with at least
# a given number of replicas.
# 2) Redis replicas are able to perform a partial resynchronization with the
# master if the replication link is lost for a relatively small amount of
# time. You may want to configure the replication backlog size (see the next
# sections of this file) with a sensible value depending on your needs.
# 3) Replication is automatic and does not need user intervention. After a
# network partition replicas automatically try to reconnect to masters
# and resynchronize with them.
#
replicaof <host> <port>
或者执行命令
127.0.0.1:6379> REPLICAOF 127.0.0.1 6379
OK
127.0.0.1:6379> SLAVEOF 127.0.0.1 6379
OK Already connected to specified master
当开始进行复制时,在后台日志中也可以看到相关信息
1847951:S 23 Mar 2022 20:46:23.652 * Connecting to MASTER 127.0.0.1:6379
1847951:S 23 Mar 2022 20:46:23.652 * MASTER <-> REPLICA sync started
1847951:S 23 Mar 2022 20:46:23.691 * Non blocking connect for SYNC fired the event.
1847951:S 23 Mar 2022 20:46:23.730 * Master replied to PING, replication can continue...
1847951:S 23 Mar 2022 20:46:23.846 * Trying a partial resynchronization (request a90c08e34bbadb9cbe86400c620bdb9b0674dc76:12844).
1847951:S 23 Mar 2022 20:46:23.885 * Full resync from master: db0eac50130903dd20adc5dbaad6c338f8056840:12792
1847951:S 23 Mar 2022 20:46:23.885 * Discarding previously cached master state.
1847951:S 23 Mar 2022 20:46:23.908 * MASTER <-> REPLICA sync: receiving 205 bytes from master
1847951:S 23 Mar 2022 20:46:23.908 * MASTER <-> REPLICA sync: Flushing old data
1847951:S 23 Mar 2022 20:46:23.908 * MASTER <-> REPLICA sync: Loading DB in memory
1847951:S 23 Mar 2022 20:46:23.908 * MASTER <-> REPLICA sync: Finished with success
需要说明的是salveof命令属于一个历史遗留问题。具体原因可以查看https://github.com/redis/redis/issues/5335.