启动客户端 zkCli.sh 文件里面的配置
# use POSIX interface, symlink is followed automatically
ZOOBIN="${BASH_SOURCE-$0}"
ZOOBIN="$(dirname "${ZOOBIN}")"
ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)"
if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then
. "$ZOOBINDIR"/../libexec/zkEnv.sh
else
. "$ZOOBINDIR"/zkEnv.sh
fi
ZOO_LOG_FILE=zookeeper-$USER-cli-$HOSTNAME.log
"$JAVA" "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" "-Dzookeeper.root.logger=${ZOO_LOG4J_PROP}" "-Dzookeeper.log.file=${ZOO_LOG_FILE}"
-cp "$CLASSPATH" $CLIENT_JVMFLAGS $JVMFLAGS
org.apache.zookeeper.ZooKeeperMain "$@"
开始的Main
// org.apache.zookeeper.ZooKeeperMain#main
public static void main(String[] args) throws IOException, InterruptedException {
ZooKeeperMain main = new ZooKeeperMain(args);
main.run();
}
Main 方法流程:
- new ZooKeeperMain 对象
- 调用 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();
}
开启 SendThread 线程
org.apache.zookeeper.ClientCnxn.SendThread#run
开启 EventThreadorg.apache.zookeeper.ClientCnxn.EventThread.run
总结 服务端源码(单机) 总体流程 具体处理流程


