Source code analysis of leader election

Source code analysis, the most important thing is to find an entrance. For zk's leader election, it is not triggered by the client, but an election is triggered when it is started. So we can go directly to the run command in the startup script zkServer.sh

ZOOMAIN is QuorumPeerMain. Then we look at it based on this entry

QuorumPeerMain.main method

In the main method, initializeAndRun is called to initialize and run

protected void initializeAndRun(String[] args) throws ConfigException, IOException{ 
	//这段代码比较简单,设置配置参数,如果args不为空,可以基于外部的配置路径来进行解析 
	QuorumPeerConfig config = new QuorumPeerConfig(); 
	if (args.length == 1) { 
		config.parse(args[0]); 
	} 
	// 这里启动了一个线程,来定时对日志进行清理,从命名来看也很容易理解 
	DatadirCleanupManager purgeMgr = new DatadirCleanupManager(config.getDataDir(), config.getDataLogDir(), config.getSnapRetainCount(), config.getPurgeInterval()); 
	purgeMgr.start(); 
	// 如果是集群模式,会调用runFromConfig.servers实际就是我们在zoo.cfg里面配置的集群节点 
	if (args.length == 1 && config.servers.size() > 0) { 
		runFromConfig(config); 
	} else {//否则直接运行单机模式 
	LOG.warn("Either no config or no 
		quorum defined in config, running "+ " in standalone mode"); 
		// there is only server in the quorum -- run as standalone 
		ZooKeeperServerMain.main(args); 
	} 
}

 

Guess you like

Origin blog.csdn.net/Leon_Jinhai_Sun/article/details/112971584