ZooKeeper API简单调用
- - 企业架构 - ITeye博客System.out.println("已经触发了" + event.getType() + "事件. System.out.println("目录结点状态:" + zk.exists("/testRootA", true));. 已有 0 人发表留言,猛击->> 这里<<-参与讨论. —软件人才免语言低担保 赴美带薪读研.
package zk.test; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.ZooKeeper; public class ZkTest { private static final int SESSION_TIMEOUT = 30000; public static void main(String[] args) throws Exception{ ZooKeeper zk = new ZooKeeper("localhost:2181", SESSION_TIMEOUT, new Watcher() { // 监控所有被触发的事件 @Override public void process(WatchedEvent event) { System.out.println("已经触发了" + event.getType() + "事件!"); } }); zk.create("/testRootA", "testRoot_data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); //创建子节点1 zk.create("/testRootA/testChild_1", "testChild_data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println(new String(zk.getData("/testRootA", false, null))); System.out.println((zk.getChildren("/testRootA/testChild_1", true))); //修改 zk.setData("/testRootA/testChild_1", "modifyTestChildOne".getBytes(), -1); System.out.println("目录结点状态:" + zk.exists("/testRootA", true)); //创建子节点2 zk.create("/testRootA/testChild_2", "testChild_2_data".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); System.out.println((zk.getChildren("/testRootA/testChild_2", true))); //删除结点 zk.delete("/testRootA/testChild_1", -1); zk.delete("/testRootA/testChild_2", -1); zk.delete("/testRootA", -1); zk.close(); } }