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();
}
}
ZooKeeper API简单调用
最新推荐文章于 2024-11-04 16:01:37 发布