本篇文章主要介绍如何使用ZooKeeper官方API来操作ZooKeeper。
maven依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.8</version>
</dependency>
ZooKeeper API
构造ZooKeeper实例
我们主要使用的是ZooKeeper 类来访问ZooKeeper 并执行一系列操作。
String hostPort = "localhost:2181,localhost:2182,localhost:2183";
int sessionTimeout = 3000;
String path = "/test/app1";
ZooKeeper zk = new ZooKeeper(hostPort, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
String path = event.getPath();
System.out.println("watch:"+event.getType()+",path:"+path);
}
});
新建znode节点
public void create(){
String data = "hello world!";
System.out.println("create data:"+data);
try {
String result = zk.create(p