Zookeeper源码解读

Posted 勿忘初心,进无止境.

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Zookeeper源码解读相关的知识,希望对你有一定的参考价值。

1.1. 客户端源码

 

1.1.1. 总体流程

 

 

 

 

 

启动客户端 zkCli.sh文件里面的配置

 

 

实际运行

 

 

  public static void main(String args[])

        throws KeeperException, IOException, InterruptedException

    {

        ZooKeeperMain main = new ZooKeeperMain(args);  

        main.run();

    }

 

 

Main方法流程:

  1. new ZooKeeperMain 对象
  2. 调用run()方法

 

ZookeeperMain的构造方法里面,重点是

  

 public ZooKeeperMain(String args[]) throws IOException, InterruptedException {

        cl.parseOptions(args);

        System.out.println("Connecting to " + cl.getOption("server"));

     //连接上ZK

        connectToZK(cl.getOption("server"));

    }
  protected void connectToZK(String newHost) throws InterruptedException, IOException {

        if (zk != null && zk.getState().isAlive()) {

            zk.close();

        }

        host = newHost;

        boolean readOnly = cl.getOption("readonly") != null;

        zk = new ZooKeeper(host,

                 Integer.parseInt(cl.getOption("timeout")),

                 new MyWatcher(), readOnly);

    }

 

 

 

最终在connectToZK方法里面也就是使用原生的Zk客户端进行连接的。

 

   public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher,

            boolean canBeReadOnly)

        throws IOException

    {

        LOG.info("Initiating client connection, connectString=" + connectString

                + " sessionTimeout=" + sessionTimeout + " watcher=" + watcher);

 

        watchManager.defaultWatcher = watcher;

 

        ConnectStringParser connectStringParser = new ConnectStringParser(

                connectString);

        HostProvider hostProvider = new StaticHostProvider(

                connectStringParser.getServerAddresses());

        cnxn = new ClientCnxn(connectStringParser.getChrootPath(),

                hostProvider, sessionTimeout, this, watchManager,

//获得和服务端连接的对象

                getClientCnxnSocket(), canBeReadOnly);

         //调用start()

        cnxn.start();

    }

 

public void start() {

    sendThread.start();

    eventThread.start();

}

 

 

 

1.1.2. 开启SendThread线程

org.apache.zookeeper.ClientCnxn.SendThread#run

 

 

 

1.1.3. 开启EventThread

org.apache.zookeeper.ClientCnxn.EventThread.run

 

 

 

1.1.4. 总结:

 

1.2. 服务端源码(单机)

1.2.1. 总体流程

 

 

1.2.2. 具体处理流程

 

以上是关于Zookeeper源码解读的主要内容,如果未能解决你的问题,请参考以下文章

ElasticJob源码部分解读-Zookeeper建立连接

zookeeperzookeeper 源码解读

Kafka Eagle 源码解读

#yyds干货盘点# mybatis源码解读:executor包(语句处理功能)

ZooKeeper 源码阅读

zookeeperzookeeper 启动 源码解读