1.引入依赖
<dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.10</version> </dependency>
2.会话连接
1 package com.karat.cn.zookeeper.zkclient; 2 3 import org.I0Itec.zkclient.ZkClient; 4 /** 5 * 创建会话(连接zookeeper) 6 * @author 开发 7 * 8 */ 9 public class SessionDemo { 10 11 private final static String CONNECTSTRING="47.107.121.215:2181"; 12 13 public static void main(String[] args) { 14 ZkClient zkClient=new ZkClient(CONNECTSTRING,4000); 15 System.out.println(zkClient+" - > success连接"); 16 } 17 }
3.节点简单操作
1 package com.karat.cn.zookeeper.zkclient; 2 3 import java.util.List; 4 import java.util.concurrent.TimeUnit; 5 6 import org.I0Itec.zkclient.IZkChildListener; 7 import org.I0Itec.zkclient.IZkDataListener; 8 import org.I0Itec.zkclient.ZkClient; 9 /** 10 * 节点操作 11 * @author Administrator 12 * 13 */ 14 public class ZkClientApiOperatorDemo { 15 16 private final static String CONNECTSTRING="47.107.121.215:2181"; 17 18 private static ZkClient getInstance(){ 19 return new ZkClient(CONNECTSTRING,10000);//10000是连接超时时间 20 } 21 22 public static void main(String[] args) throws InterruptedException { 23 ZkClient zkClient=getInstance();//连接 24 //zkClient.createEphemeral("/zkClient");//创建临时节点 25 //zkClient中提供递归创建父节点的功能 26 //zkClient.createPersistent("/zkClient/a/b/c/d",true);//创建持久化节点 27 //删除节点 28 //zkClient.delete("/zkClient"); 29 //递归删除节点 30 //zkClient.deleteRecursive("/zkClient"); 31 //获取子节点 32 List<String> list=zkClient.getChildren("/zkClient/a"); 33 System.out.println(list); 34 35 36 //watcher(订阅获取) 37 zkClient.subscribeDataChanges("/node", new IZkDataListener() { 38 39 @Override 40 public void handleDataDeleted(String dataPath) throws Exception { 41 // TODO Auto-generated method stub 42 43 } 44 45 @Override 46 public void handleDataChange(String dataPath, Object data) throws Exception { 47 // TODO Auto-generated method stub 48 System.out.println("节点名称:"+dataPath+"->节点修改后的值"+data); 49 } 50 }); 51 52 zkClient.writeData("/node", "123");//修改节点的数据 53 TimeUnit.SECONDS.sleep(2);//上述事件是异步的,需要睡两秒 54 55 zkClient.subscribeChildChanges("/node", new IZkChildListener() { 56 57 @Override 58 public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception { 59 // TODO Auto-generated method stub 60 61 } 62 }); 63 } 64 }
原文地址:https://www.cnblogs.com/LJing21/p/10537254.html
时间: 2024-11-06 13:57:31