使用cli操作zookeeper
//创建节点
create /test "hello"
create /test/dr1 null
create -s /test/index null
create -s -e /test/index null
get /test/dr watch
set /test/dr 111
ls2 /test watch
ls /test
delete /test
rmr /test
java操作zookeeper
public ZooKeeper connect(String host) throws IOException,InterruptedException {
zoo = new ZooKeeper(host,5000,new Watcher() {
public void process(WatchedEvent we) {
if (we.getState() == Event.KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
});
connectedSignal.await();
return zoo;
}
//创建节点,在创建时需要指定节点的安全权限,节点类型(是否为临时节点、是否为顺序节点)。返回的为节点名称(可能和创建的节点名称不同,例如顺序节点)
String createStr=zooKeeper.create("/test/java1","hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL)
//在节点上设置监听
zooKeeper.getData(PATH, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println(watchedEvent.getType())
try {
System.out.println(new String(finalZooKeeper.getData(PATH,false,null)))
} catch (KeeperException e) {
e.printStackTrace()
} catch (InterruptedException e) {
e.printStackTrace()
}
}
},null)
//修改数据前需要先判断节点是否存在,同时获取到节点上的版本号(可以从stat中获取)
Stat stat=zooKeeper.exists(PATH,false)
System.out.println(stat.getVersion())
zooKeeper.setData(PATH,"hello zk".getBytes(),stat.getVersion())
//获取所有的子节点
List<String> childrenList=zooKeeper.getChildren("/test",false)
//删除节点,删除时也需要获取到版本号
zooKeeper.delete("/test/dr",stat.getVersion())