三、leader选举分析
在我理解首先在选举时,并不能用到paxos算法,paxos里选总统也好,zk选leader也好,跟搞个提案让大部分人同意是有区别的。选主才能保证不会出现多proposer的并发提案冲突
谁去作为proposer发提案?是paxos算法进行下去的前提。fast paxosfast paxos而提出提案让大部分follower同意则可用到类似paxos的算法实现一致性。zookeeper使用的是Zab算法实现一致性。
zk的选主策略:
there can be at most one leader (proposer) at any time, and we guarantee this by making sure that a quorum of replicas recognize the leader as a leader by committing to an epoch change. This change in epoch also allows us to get unique zxids since the epoch forms part of the zxid.
每个server有一个id,收到提交的事务时则有一个zxid,随更新数据的变动,事务编号递增,server id各不同。首先选zxid最大的作为leader,如果zxid比较不出来,则选server id最大的为leader
zxid包含一个epoch数字,epoch指示一个server作为leader的时期,随新的leader诞生而递增。
再看代码:
四、zookeeper数据更新原理分析
了解完选主的做法后,来了解下同步数据的做法,同步数据则采用Zab协议:Zookeeper Atomic broadcast protocol,是个类似两阶段提交的协议:
The leader sends a PROPOSAL message, p, to all followers.
Upon receiving p, a follower responds to the leader with an ACK, informing the
leader that it has accepted the proposal.
Uponreceivingacknowledgmentsfromaquorum(thequorumincludestheleader
itself), the leader sends a message informing the followers to COMMIT it.
跟paxos的区别是leaer发送给所有follower,而不是大多数,所有follower都要确认并通知leader,而不是大多数。
保证机制:按顺序广播的两个事务,T 和 Tʹ ,T在前则Tʹ 生效前必须提交T。如果有一个server 提交了T 和 Tʹ ,则所有其他server必须也在Tʹ前提交T。
五、leader的探活
为解决leader crash的问题,避免出现多个leader导致事务混乱,Zab算法保证:
1、新事务开启时,leader必须提交上个epoch期间提交的所有事务
2、任何时候都不会有两个leader同时获得足够多的支持者。
一个新leader的起始状态需要大多数server同意
六、observer
zk里的第三种角色,观察者和follower的区别就是没有选举权。它主要是1、为系统的读请求扩展性存在 2、满足多机房部署需求,中心机房部署leader、follower,其他机房部署observer,读取配置优先读本地。
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-37027-3.html
说的透彻
言语恰当