raft 一致性算法

选举master过程

redis使用raft leader election进行master选举。

概念:

一个cluster中有多个node,最终状态有一个leader,多个follower。

leader通过heartbeat周期性和follower通信。

node有三种状态:leader,follower,candidate(leader候选人)

什么时候开始选举?

如果followers在一定时间没有接收到leader的heartbeat message(称之为选举超时election timeout,比如election timeout 是一个150ms-300ms中的随机数,为了避免)followers认为cluster中没有leader,follower变成candidate,发起选举,要求其他节点进行投票。

选举过程:

某一个或多个followers的election timeout达到,该follower变为candidate,开始自己的任期(当前term+1),并向其他node发送请求投票(Request Vote)的message,让他们给自己投票。

如果接收到Request Vote的node本term内没有投票,那么该node投票给这个candidate,同时重置自身的election timeout。

一旦某一candidate获得多数投票,它成为leader。

一轮投票的结果可能有:

1.某一node获得majority vote,成为leader。

2.没有节点获得majority vote。candidate到达自己的election timeout,再次开始重新选举。因为每个node的timeout是一个随机值,能够确保不会产生无限的选举循环,在一定数量的选举轮次后能够选出leader。

选举规则:

一旦一个candidate获得多数投票,它成为leader。

每个node在一个term内最多投票一次。

成为leader的node通过发送heartbeat给其他node,通知leader选举完成,并重置其它node的election timeout。

日志复制

client发送change到leader,leader记录该change到自身的log(称之为一个log entry),之后通过heartbeat发送该change到followers。

在多数followers回复已接收到该change时(acknowledaged),leader的log中的一个entry被标记为committed。leader 发送回复给client,声明该change已完成。一旦follower知道log entry已经被committed,那么他也会将这个log entry应用到本地的log中。

Refs:

https://www.jianshu.com/p/32813075a7e7

https://github.com/maemual/raft-zh_cn/blob/master/raft-zh_cn.md

http://thesecretlivesofdata.com/raft/

原文地址:https://www.cnblogs.com/cnsec/p/13547566.html