Redis主从同步

Redis主从同步有三个主要的特点

  • master-slave保持链接的时候,master会将引起redis数据集发生改变的命令发送到slave,保持数据同步
  • 网络断开首先进行一次增量同步
  • 增量同步失败进行一次全量同步
    • master首先生成一个rdb快照,发送给slave,slave消化完之后
    • 将这之间堆积的命令再发送到slave
    • 之后保持增量同步

      命令

      1. slaveof IP PORT
  • slaveof no one : 将slave提升为master. 故障转移的时候使用该命令将从节点提升为master节点
  • slaveof IP PORT : 指定IP:PORT作为当前节点的master节点.

发出命令后并不是实时连接到master,只是将master的IP和PORT设置上去,链接发生在定时监测中,Redis会每隔1秒发起一次监测. 链接是否断开然后进行重新链接。

  1. /* Slave replication state. Used in server.repl_state for slaves to remember
  2. * what to do next. */
  3. #define REPL_STATE_NONE 0 /* No active replication */
  4. #define REPL_STATE_CONNECT 1 /* Must connect to master */
  5. #define REPL_STATE_CONNECTING 2 /* Connecting to master */
  6. /* --- Handshake states, must be ordered --- */
  7. #define REPL_STATE_RECEIVE_PONG 3 /* Wait for PING reply */
  8. #define REPL_STATE_SEND_AUTH 4 /* Send AUTH to master */
  9. #define REPL_STATE_RECEIVE_AUTH 5 /* Wait for AUTH reply */
  10. #define REPL_STATE_SEND_PORT 6 /* Send REPLCONF listening-port */
  11. #define REPL_STATE_RECEIVE_PORT 7 /* Wait for REPLCONF reply */
  12. #define REPL_STATE_SEND_IP 8 /* Send REPLCONF ip-address */
  13. #define REPL_STATE_RECEIVE_IP 9 /* Wait for REPLCONF reply */
  14. #define REPL_STATE_SEND_CAPA 10 /* Send REPLCONF capa */
  15. #define REPL_STATE_RECEIVE_CAPA 11 /* Wait for REPLCONF reply */
  16. #define REPL_STATE_SEND_PSYNC 12 /* Send PSYNC */
  17. #define REPL_STATE_RECEIVE_PSYNC 13 /* Wait for PSYNC reply */
  18. /* --- End of handshake states --- */
  19. #define REPL_STATE_TRANSFER 14 /* Receiving .rdb from master */
  20. #define REPL_STATE_CONNECTED 15 /* Connected to master */
  21. /* Replication cron function, called 1 time per second. */
  22. void replicationCron(){
  23. }

Reference