1.配置依赖:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.13</version> <!--日志应用冲突,排除zookeeper默认应用log4j --> <exclusions> <exclusion> <artifactId>log4j</artifactId> <groupId>log4j</groupId> </exclusion> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.10</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2.zkClient应用模拟类:
package com.cc.springbootzookeeperclient; import lombok.extern.slf4j.Slf4j; import org.I0Itec.zkclient.IZkChildListener; import org.I0Itec.zkclient.ZkClient; import org.I0Itec.zkclient.ZkConnection; import org.apache.zookeeper.CreateMode; import java.util.List; @Slf4j public class ZkClientTest { /** * 链接字符串(链接集群用逗号隔开):192.168.1.11:2182,192.168.1.11:2183 */ public static final String ZK_HOST = "192.168.1.11:2182,192.168.1.11:2183,192.168.1.11:2184,192.168.1.11:2185"; public static void main(String[] args) throws InterruptedException { /** * 1.建立连接,方式很多,此处用最简单的方式 */ ZkClient zkClient = new ZkClient(ZK_HOST); //ZkClient zkClient = new ZkClient(new ZkConnection(ZK_HOST),5000); /**2.创建节点 *可以递归创建节点,但是不能赋值 */ zkClient.create("/zk","test",CreateMode.PERSISTENT); //直接创建持久化节点: zkClient.createPersistent("/zkTest","zkby"); //直接递归创建持久化节点,不可以赋值 zkClient.createPersistent("/zkoder/oder",true); /**3.设置修改节点内容 * */ zkClient.writeData("/zkoder/oder","modify data"); /**4.获取子节点 * */ List<String> list = zkClient.getChildren("/zkoder"); log.info("childrens:{}",list); /**5.删除节点 * 可以递归删除 */ //普通删除 //zkClient.delete("/zk"); //递归删除,“删除参数节点及节点以下的子节点”,添加父节点就ok zkClient.deleteRecursive("/zkoder"); /** * zkClient中watch(监听)的使用 */ zkClient.subscribeChildChanges("/test", new IZkChildListener() { @Override public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception { log.info("--------------parent node:{}",parentPath); log.info("--------------current childs:{}",currentChilds); } }); //异常抛出了,方便演示 Thread.sleep(3000); zkClient.createPersistent("/test/a"); Thread.sleep(3000); zkClient.deleteRecursive("/test"); Thread.sleep(Integer.MAX_VALUE); } }