Redis作为一个高性能、高可用的分布式缓存数据库,提供了主从复制的能力。被复制的节点成为主(master)节点,复制的节点称为从(slave)节点。
未命名文件 (1).svg
Redis主从复制除了保障服务的稳定性之外,还可以做读写分离,进行扩容,关于Redis集群节点的拆分可以按照AKF原则来拆分,这在后面的实战部分会进行详细描述,这一部分主要分析Redis主从复制的过程及实现细节。

开启功能

Redis主从复制可以通过配置文件配置,也可以通过客户端发送命令来触发,一旦服务器节点作为从节点开始复制,就无法再写入数据。

  1. # Master-Replica replication. Use replicaof to make a Redis instance a copy of
  2. # another Redis server. A few things to understand ASAP about Redis replication.
  3. #
  4. # +------------------+ +---------------+
  5. # | Master | ---> | Replica |
  6. # | (receive writes) | | (exact copy) |
  7. # +------------------+ +---------------+
  8. #
  9. # 1) Redis replication is asynchronous, but you can configure a master to
  10. # stop accepting writes if it appears to be not connected with at least
  11. # a given number of replicas.
  12. # 2) Redis replicas are able to perform a partial resynchronization with the
  13. # master if the replication link is lost for a relatively small amount of
  14. # time. You may want to configure the replication backlog size (see the next
  15. # sections of this file) with a sensible value depending on your needs.
  16. # 3) Replication is automatic and does not need user intervention. After a
  17. # network partition replicas automatically try to reconnect to masters
  18. # and resynchronize with them.
  19. #
  20. replicaof <host> <port>

或者执行命令

  1. 127.0.0.1:6379> REPLICAOF 127.0.0.1 6379
  2. OK
  3. 127.0.0.1:6379> SLAVEOF 127.0.0.1 6379
  4. OK Already connected to specified master

当开始进行复制时,在后台日志中也可以看到相关信息

  1. 1847951:S 23 Mar 2022 20:46:23.652 * Connecting to MASTER 127.0.0.1:6379
  2. 1847951:S 23 Mar 2022 20:46:23.652 * MASTER <-> REPLICA sync started
  3. 1847951:S 23 Mar 2022 20:46:23.691 * Non blocking connect for SYNC fired the event.
  4. 1847951:S 23 Mar 2022 20:46:23.730 * Master replied to PING, replication can continue...
  5. 1847951:S 23 Mar 2022 20:46:23.846 * Trying a partial resynchronization (request a90c08e34bbadb9cbe86400c620bdb9b0674dc76:12844).
  6. 1847951:S 23 Mar 2022 20:46:23.885 * Full resync from master: db0eac50130903dd20adc5dbaad6c338f8056840:12792
  7. 1847951:S 23 Mar 2022 20:46:23.885 * Discarding previously cached master state.
  8. 1847951:S 23 Mar 2022 20:46:23.908 * MASTER <-> REPLICA sync: receiving 205 bytes from master
  9. 1847951:S 23 Mar 2022 20:46:23.908 * MASTER <-> REPLICA sync: Flushing old data
  10. 1847951:S 23 Mar 2022 20:46:23.908 * MASTER <-> REPLICA sync: Loading DB in memory
  11. 1847951:S 23 Mar 2022 20:46:23.908 * MASTER <-> REPLICA sync: Finished with success

需要说明的是salveof命令属于一个历史遗留问题。具体原因可以查看https://github.com/redis/redis/issues/5335.