首先先添加pom依赖:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.13</version>
</dependency>
</dependencies>
接着编写代码
package org.example;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class ZkClient {
private ZooKeeper zkCli;
private static final String CONNECT_STRING="ip:2181";
private static final int SESSION_TIMEOUT = 2000;
@Before
public void Before() throws IOException {
zkCli=new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, e->{
});
}
@Test
//得到子节点
public void getChildren() throws KeeperException, InterruptedException {
List<String> children = zkCli.getChildren("/", true);
System.out.println("----------------------------");
for (String child : children) {
System.out.println(child);
}
}
@Test
//创造结点
public void create() throws KeeperException, InterruptedException {
String s = zkCli.create("/root2", "data2".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println(s);
Thread.sleep(Long.MAX_VALUE);
System.out.println("创建成功");
}
@Test
//获取结点值
public void get() throws KeeperException, InterruptedException {
byte[] data = zkCli.getData("/root1", true, new Stat());
String s = new String(data);
System.out.println(s);
}
@Test
//设置结点值
public void set() throws KeeperException, InterruptedException {
Stat exists = zkCli.exists("/root1", true);
zkCli.setData("/root1", "data2".getBytes(), exists.getVersion());
System.out.println("设置成功");
}
@Test
//删除结点
public void delete() throws KeeperException, InterruptedException {
Stat stat = zkCli.exists("/root1", false);
if (stat != null) {
zkCli.delete("/root1",stat.getVersion());
}
System.out.println("删除成功");
}
@Test
//判断节点是否存在
public void exists() throws KeeperException, InterruptedException {
Stat exists = zkCli.exists("/root1", false);
if (exists != null){
System.out.println("该节点存在");
}else {
System.out.println("该节点不存在");
}
}
}
上面的ip地址按照自己的ip地址设定即可!!!