Zookeeper_閱讀源碼第一步_在 IDE 裏啓動 zkServer(單機版)

 
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


轉載請註明出處命令行

相關文章
相關標籤/搜索