pom.xml
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
<version>0.10</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
</dependency>
版本:zookeeper-3.5.7
import org.I0Itec.zkclient.IZkDataListener; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.serialize.SerializableSerializer; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.Stat; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; public class TestZkClient { private ZkClient zkClient = null; @Test public void test() throws IOException { //zk server 服务器ip地址 端口号 //会话超时时间 //连接超时时间 //序列化方式 对象 zkClient = new ZkClient("192.168.0.115:2181",60000*30,60000,new SerializableSerializer()); System.out.println(zkClient); //监听节点变化 //需要通过java修改zookeeper数据,才能监听到 zkClient.subscribeDataChanges("/node1", new IZkDataListener() { //节点数据变化时触发 @Override public void handleDataChange(String s, Object o) throws Exception { System.out.println("change Node: " + s); System.out.println("change data: " + o); } //节点数据删除时触发 @Override public void handleDataDeleted(String s) throws Exception { System.out.println("delete Node: " + s); } }); //testWriteNodeData(); //testDeleteNode(); //System.in.read(); //阻塞当前监听,使得监听不会停止 //testCreateNode(); //testDeleteNode(); //testFindNode(); //testFindNodeData(); //testFindNodeAndStat(); //testWriteNodeData(); zkClient.close(); } //创建zk节点 public void testCreateNode() { //创建持久节点 String node1 = zkClient.create("/node1", "xiaochen", CreateMode.PERSISTENT); System.out.println(node1); //创建持久顺序节点 String node2 = zkClient.create("/node1/names","zhangsan",CreateMode.PERSISTENT_SEQUENTIAL); System.out.println(node2); //创建临时节点 String node3 = zkClient.create("/node1/lists","xiaoxiao",CreateMode.EPHEMERAL); System.out.println(node3); //创建临时顺序节点 String node4 = zkClient.create("/node1/lists1","xiaoming",CreateMode.EPHEMERAL_SEQUENTIAL); System.out.println(node4); } //删除zk节点 public void testDeleteNode() { //删除没有子节点的节点 如果节点有子节点会报错 /*boolean b1 = zkClient.delete("/node1"); System.out.println(b1);*/ //遍历删除节点信息 boolean b2 = zkClient.deleteRecursive("/node1"); System.out.println(b2); } //查询zk节点 public void testFindNode() { List<String> children = zkClient.getChildren("/"); for (String child : children) { System.out.println(child); } } //查询zk某个节点数据 //注意:通过java客户端操作时,需要保证节点存储的数据和获取节点时的数据序列化方式一致 public void testFindNodeData() { Object data = zkClient.readData("/node1"); System.out.println(data); } //查询zk节点数据并获取状态信息 public void testFindNodeAndStat() { Stat stat = new Stat(); Object data = zkClient.readData("/node1",stat); System.out.println(data); System.out.println(stat); } //修改zk节点数据 public void testWriteNodeData() { zkClient.writeData("/node1",233); } }