<font style="color:rgb(68, 68, 68);">Redis主从复制</font>

<font style="color:rgb(51, 51, 51);">主从复制,是指将一台Redis</font><font style="color:rgb(0, 164, 255);">服务器</font><font style="color:rgb(51, 51, 51);">的数据,复制到其他的Redis服务器。前者称为主节点(master),后者称为从节点(slave),数据的复制是单向的,只能由主节点到从节点。</font>

  • <font style="color:rgb(35, 38, 59);">一个master可以有多个slave</font>
  • <font style="color:rgb(35, 38, 59);">一个slave只能有一个master</font>
  • <font style="color:rgb(35, 38, 59);">数据流向是单向的,master到slave</font>

<font style="color:rgb(51, 51, 51);">主从复制架构图:</font>

m4gxkigx.png

<font style="color:rgb(35, 38, 59);">redis为什么需要主从复制</font>

(1)、Redis虽然读写的速度都很快,单节点的Redis能够支撑QPS大概在5w左右,如果上千万的用户访问,Redis就承载不了,成为了高并发的瓶颈。

(2)、单节点的Redis不能保证高可用,当Redis因为某些原因意外宕机时,会导致缓存不可用

(3)、CPU的利用率上,单台Redis实例只能利用单个核心,这单个核心在面临海量数据的存取和管理工作时压力会非常大。

<font style="color:rgb(51, 51, 51);">工作原理</font>

  1. <font style="color:rgb(51, 51, 51);">当从服务器连接主服务器时,发送SYNC命令;</font>
  2. <font style="color:rgb(51, 51, 51);">主服务器接收到SYNC命名后,开始执行BGSAVE命令生成RDB文件并使用缓冲区记录此后执行的所有写命令;</font>
  3. <font style="color:rgb(51, 51, 51);">主服务器BGSAVE执行完后,向所有从服务器发送快照文件,并在发送期间继续记录被执行的写命令;</font>
  4. <font style="color:rgb(51, 51, 51);">从服务器收到快照文件后丢弃所有旧数据,载入收到的快照;</font>
  5. <font style="color:rgb(51, 51, 51);">主服务器快照发送完毕后开始向从服务器发送缓冲区中的写命令;</font>
  6. <font style="color:rgb(51, 51, 51);">从服务器完成对快照的载入,开始接收命令请求,并执行来自主服务器缓冲区的写命令;(从服务器初始化完成)</font>
  7. <font style="color:rgb(51, 51, 51);">主服务器每执行一个写命令就会向从服务器发送相同的写命令,从服务器接收并执行收到的写命令 (从服务器初始化完成后的操作)</font>

<font style="color:rgb(51, 51, 51);">工作原理图</font>

m4gxlucc.png

<font style="color:rgb(51, 51, 51);">主从复制优缺点</font>

<font style="color:rgb(51, 51, 51);">优点</font>

<font style="color:rgb(25, 27, 31);">(1)配置简单,易于实现</font>

<font style="color:rgb(25, 27, 31);">(2)实现数据备份和冗余,提高数据可靠性</font>

<font style="color:rgb(25, 27, 31);">(3)实现</font><font style="color:rgb(25, 27, 31);">读写分离</font><font style="color:rgb(25, 27, 31);">,提高系统性能</font>

<font style="color:rgb(51, 51, 51);">缺点</font>

<font style="color:rgb(25, 27, 31);">(1)在主节点发生故障时,只能手动切换,故障恢复时间长,必须借助其他手段完成自动切换</font>

<font style="color:rgb(25, 27, 31);">(2)所有的写操作都在主节点上,主节点的压力大,会成为性能瓶颈</font>

<font style="color:rgb(25, 27, 31);">(3)所有节点都保持同一份数据,不能进行数据分片,单机容量即为整个集群的容量</font>