Zookeeper是开源的,若是想多了解Zookeeper或看它的源码,最好是能找到它的源码并在 IDE 里启动,能够debug看它咋执行的,可以帮助你理解其原理。
准备源码
因此咱们很容易搞到它的源码,例如咱们从
GitHub上获取源码 或 从
Apache官网获取可运行版本的压缩包(内含源码)。这里我下载的是3.4.13版本的,从GitHub拉取源码在idea运行时,编译不能经过,缺乏类,缘由是有些类须要data包下的类,可是没有这个data包,因此编译过不了,也就没法测试。


因此选择第二种,下载到 zookeeper-3.4.13.tar.gz 而后解压,和从GitHub上下载的仍是有些差异的。


导入到IDE
而后将下载好的源码导入到idea。需建立resources目录把 conf 目录下的 log4j.properties 复制到该目录下,不然启动异常报找不到log4j.properties的错。

准备启动
而后咱们找到 org.apache.zookeeper.server.quorum.QuorumPeerMain 这个类,这个是 zookeeper 的主入口,当你用脚本启动时其实运行的也是这个类。
题外话,看看启动脚本。
zkCli.sh脚本文件
zkCli.cmdgit

回来,咱们打开这个类会看到有个main方法,看注释,咱们须要在启动时指定配置文件。
/** * To start the replicated server specify the configuration file name on * the command line.要启动复制的服务器,请在命令行上指定配置文件名。 * @param args path to the configfile 配置文件的路径 */
public static void main(String[] args) { QuorumPeerMain main = new QuorumPeerMain(); try { main.initializeAndRun(args); } //some catchs... //some codes ...
} LOG.info("Exiting normally"); System.exit(0); }
配置启动参数
首先运行这个类的main方法,会报错,说非法参数哦,以下github

配置一下,在 Program arguments里添加配置文件的路径。apache

正式启动
再启动就成功了服务器

测试是否启动成功
咱们开启客户端连一下ide

连上了,而且有三个节点。测试
这段代码是一些初始化,并判断是单机启动仍是集群启动idea
protected void initializeAndRun(String[] args) throws ConfigException, IOException { QuorumPeerConfig config = new QuorumPeerConfig(); if (args.length == 1) { config.parse(args[0]); }
// Start and schedule the the purge task DatadirCleanupManager purgeMgr = new DatadirCleanupManager(config .getDataDir(), config.getDataLogDir(), config .getSnapRetainCount(), config.getPurgeInterval()); purgeMgr.start();
if (args.length == 1 && config.servers.size() > 0) { System.out.println("=======集群模式======="); runFromConfig(config); } else { System.out.println("=======单机模式======="); LOG.warn("Either no config or no quorum defined in config, running " + " in standalone mode"); ZooKeeperServerMain.main(args); } } |
单机版启动,到这里就结束了。篇幅缘由,集群版下一篇再见。spa
转载请注明出处命令行