1. 启动类org.apache.zookeeper.server.quorum.QuorumPeerMain分析
启动类的Main方法调用了 initializeAndRun 方法,initializeAndRun 方法中主要做了三件事情:解析配置文件,启动历史文件清理器和调用 ZooKeeperServerMain 的main方法启动ZooKeeper服务。
解析配置文件:
QuorumPeerConfig config = new QuorumPeerConfig();
if (args.length == 1) {
config.parse(args[0]);//args[0]参数是配置文件的名称
}
紧接着我们进入parse方法看下QuorumPeerConfig是如何解析配置文件的(仅贴出了关键代码)
File configFile = new File(path);
...
Properties cfg = new Properties();
FileInputStream in = new FileInputStream(configFile);
try {
cfg.load(in);
} finally {
in.close();
}
parseProperties(cfg);
从上面的代码片段可以看出,parse方法通过文件输入流FileInputStream将配置文件读入到一个Properties文件中,并将这个配置文件传入parseProperties方法中继续处理。
public void parseProperties(Properties zkProp)
throws IOException, ConfigException {
....
for (Entry<Object, Object> entry : zkProp.entrySet()) {
String key = entry.getKey().toString().trim();
String value = entry.getValue().toString().trim();
if (key.equals("dataDir")) {
dataDir = value;
}
...
...
}
parseProperties方法中通过遍历Properties文件中的条目为QuorumPeerConfig类中的相应属性进行赋值。
启动历史文件清理器:
// Start and schedule the the purge task
DatadirCleanupManager purgeMgr = new DatadirCleanupManager(config
.getDataDir(), config.getDataLogDir(), config
.getSnapRetainCount(), config.getPurgeInterval());
purgeMgr.start();
这个历史文件清理器的分析先略过
启动ZooKeeper服务器:
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);
}
config.servers是一个HashMap, 在配置文件解析时已被初始化,其中key是机器节点的id,也就是data目录下myid文件中保存的数字,value是QuorumServer对象,代表了每一个zookeeper服务器节点。显然config.servers如果为空则说明是单机版启动,直接执行ZooKeeperServerMain的main方法进行启动。
网友评论