Seeing this method, do you feel the light in your eyes? That’s right, after such a long period of preparation, I finally entered the leader election method.
synchronized public void startLeaderElection() {
try {
//构建一个票据,用于投票
currentVote = new Vote(myid,
getLastLoggedZxid(), getCurrentEpoch());
} catch(IOException e) {
RuntimeException re = new
RuntimeException(e.getMessage());
re.setStackTrace(e.getStackTrace());
throw re;
}
//这个getView返回的就是在配置文件中配置的server.myid=ip:port:port。view在哪里解析的呢?
for (QuorumServer p : getView().values()) {
if (p.id == myid) {//获得当前zkserver myid对应的ip地址
myQuorumAddr = p.addr;
break;
}
}
if (myQuorumAddr == null) {
throw new RuntimeException("My id " + myid + " not in the peer list");
}
//根据electionType匹配对应的选举算法,electionType默认值为3.可以在配置文件中动态配置
if (electionType == 0) {
try {
udpSocket = new
DatagramSocket(myQuorumAddr.getPort());
responder = new ResponderThread();
responder.start();
} catch (SocketException e) {
throw new RuntimeException(e);
}
}
this.electionAlg = createElectionAlgorithm(electionType);
}