投票完毕之后如果收到的票数大于一半,那么就会晋升为leader,调用becomeLeader方法。
private void becomeLeader() { Requires.requireTrue(this.state == State.STATE_CANDIDATE, "Illegal state: " + this.state); LOG.info("Node {} become leader of group, term={}, conf={}, oldConf={}.", getNodeId(), this.currTerm, this.conf.getConf(), this.conf.getOldConf()); // cancel candidate vote timer //晋升leader之后就会把选举的定时器关闭了 stopVoteTimer(); //设置当前的状态为leader this.state = State.STATE_LEADER; this.leaderId = this.serverId.copy(); //复制集群中设置新的任期 this.replicatorGroup.resetTerm(this.currTerm); //遍历所有的集群节点 for (final PeerId peer : this.conf.listPeers()) { if (peer.equals(this.serverId)) { continue; } LOG.debug("Node {} add replicator, term={}, peer={}.", getNodeId(), this.currTerm, peer); //如果成为leader,那么需要把自己的日志信息复制到其他节点 if (!this.replicatorGroup.addReplicator(peer)) { LOG.error("Fail to add replicator, peer={}.", peer); } } // init commit manager this.ballotBox.resetPendingIndex(this.logManager.getLastLogIndex() + 1); // Register _conf_ctx to reject configuration changing before the first log // is committed. if (this.confCtx.isBusy()) { throw new IllegalStateException(); } this.confCtx.flush(this.conf.getConf(), this.conf.getOldConf()); //如果是leader了,那么就要定时的检查不是有资格胜任 this.stepDownTimer.start(); }这个方法里面首先会停止选举定时器,然后设置当前的状态为leader,并设值任期,然后遍历所有的节点将节点加入到复制集群中,最后将stepDownTimer打开,定时对leader进行校验是不是又半数以上的节点响应当前的leader。
好了,到这里就讲完了,希望下次还可以see you again~