zk源码环境搭建

时间:2022-09-18 14:52:13

zk不是使用maven管理的。

将zk的src下的代码导入eclipse,lib下的jar包导入工程。

zk源码环境搭建

QuorumPeerMain类的main方法是入口,启动了zk的server,参数是conf文件的路径,

例如:org.apache.zookeeper.server.quorum.QuorumPeerMain /usr/local/software/zookeeper-3.4.3/bin/../conf/zoo.cfg

客户端入口程序类是ZooKeeperMain。

测试代码:

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;

public class CreateGroup implements Watcher {
private static final int SESSION_TIMEOUT = 5000;
private ZooKeeper zk;
private CountDownLatch connectedSignal = new CountDownLatch(1);

public void connect(String hosts) throws IOException, InterruptedException {
zk
= new ZooKeeper(hosts, SESSION_TIMEOUT, this);
connectedSignal.await();
}

@Override
public void process(WatchedEvent event) { // Watcher interface
if (event.getState() == KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}

public void create(String groupName) throws KeeperException,
InterruptedException {
String path
= "/" + groupName;
String createdPath
= zk.create(path, null/* data */,
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(
"Created " + createdPath);
}

public void close() throws InterruptedException {
zk.close();
}

public static void main(String[] args) throws Exception {
CreateGroup createGroup
= new CreateGroup();
createGroup.connect(args[
0]);
createGroup.create(args[
1]);
createGroup.close();
}
}

 

参数:localhost fan,链接本地,创建zkNode:fan。

zk支持在window下开发使用,不建议生产使用。$ZOOKEEPER_HOME/bin/zkCli.cmd -server host:port  访问zk服务器。