package watcher; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; public class Zk2{ /* * 定义变量 */ private static String connectString = "192.168.1.10:2181"; private static int sessionTimeout = 55555; private ZooKeeper zookeeper; /* * 初始化zookeeper */ public Zk2() throws Exception{ zookeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher(){ public void process(WatchedEvent arg0) { // TODO Auto-generated method stub try { System.out.println("持久节点Zk1上的子节点为::"+zookeeper.getChildren("/zk1", this)); } catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}); } /* * 创建持久节点 */ public void createPNode() throws Exception { if((zookeeper.exists("/zk1", false)) == null){ zookeeper.create("/zk1", "mybook".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } /* * 创建临时子节点 */ public void createENode() throws Exception { System.out.println("创建临时子节点:"); for (int i=0; i < 10; i++) { String str = String.valueOf(i); zookeeper.create("/zk1/"+str,"myconputer".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); Thread.sleep(500); } System.out.println("临时子节点创建完毕!"+"\n"); } /* * 删除临时子节点 */ public void deleteENode() throws Exception { System.out.println("开始删除临时子节点:"); for (int i=0; i < 10; i++) { String str = String.valueOf(i); zookeeper.delete("/zk1/"+str,-1); Thread.sleep(500); } System.out.println("临时子节点删除完毕!"); } /* * 关闭连接 */ public void closeZk() throws Exception{ zookeeper.close(); } public static void main(String args[]) throws Exception { // 实例化一个Zookeeper实例 Zk2 baolibin = new Zk2(); // 创建持久节点 baolibin.createPNode(); // 创建临时节点 baolibin.createENode(); // 休眠 给删除节点操作 设定执行时间 Thread.sleep(5000); // 删除临时节点 baolibin.deleteENode(); //休眠 给关闭Zookeeper连接 设定执行时间 Thread.sleep(5000); //关闭 baolibin.closeZk(); } }
log4j:WARN No appenders could be found for logger (org.apache.zookeeper.ZooKeeper). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. 创建临时子节点: 持久节点Zk1上的子节点为::[] 持久节点Zk1上的子节点为::[0] 持久节点Zk1上的子节点为::[1, 0] 持久节点Zk1上的子节点为::[2, 1, 0] 持久节点Zk1上的子节点为::[3, 2, 1, 0] 持久节点Zk1上的子节点为::[3, 2, 1, 0, 4] 持久节点Zk1上的子节点为::[3, 2, 1, 0, 5, 4] 持久节点Zk1上的子节点为::[3, 2, 1, 0, 6, 5, 4] 持久节点Zk1上的子节点为::[3, 2, 1, 0, 7, 6, 5, 4] 持久节点Zk1上的子节点为::[3, 2, 1, 0, 7, 6, 5, 4, 8] 持久节点Zk1上的子节点为::[3, 2, 1, 0, 7, 6, 5, 4, 9, 8] 临时子节点创建完毕! 开始删除临时子节点: 持久节点Zk1上的子节点为::[3, 2, 1, 7, 6, 5, 4, 9, 8] 持久节点Zk1上的子节点为::[3, 2, 7, 6, 5, 4, 9, 8] 持久节点Zk1上的子节点为::[3, 7, 6, 5, 4, 9, 8] 持久节点Zk1上的子节点为::[7, 6, 5, 4, 9, 8] 持久节点Zk1上的子节点为::[7, 6, 5, 9, 8] 持久节点Zk1上的子节点为::[7, 6, 9, 8] 持久节点Zk1上的子节点为::[7, 9, 8] 持久节点Zk1上的子节点为::[9, 8] 持久节点Zk1上的子节点为::[9] 持久节点Zk1上的子节点为::[] 临时子节点删除完毕!