zookeeper简单客户端API
程序员文章站
2022-06-06 09:20:50
...
public class ZKclient{
public static void main(String[] args){
private String connectString="ip1:2181,ip2:2181,ip3:2181";
private int sessionTimeout = 3000;
ZooKeeper zkCli = null;
//初始化客户端
public void init() throws IOException {
zkCli = new ZooKeeper(connectString,sessionTimeout,new Watcher(){
//回调监听
@Override
public void process(WatchedEvent event){
System.out.println(event.getPath() + "\t" + event.getState() + "\t" + event.getType());
try{
list<String> children = zkCli.getChildren("/",true);
for(String child : children){
System.out.println(child);
}
} catch(KeeperException e ){
e.printStackTrace();
} catch(InterruptException e) {
e.printStackTrace();
}
}
});
}
//创建子节点
public void createZnode() throws KeeperException, InterruptException {
//第三个参数为应答方式,第四个为节点类型-s/-e
String path = zkCli.create("/bbq", "shaokao".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSIENTENT);
System.out.println(path);
}
//获取子节点
public void getChild() throws KeeperException, InterruptException {
list<String> children = zkCli.getChildren("/", true);
for(String child : children){
System.out.println(child);
}
Thread.sleep(Long.MAX_VALUE);//永久监听
}
//删除节点
public void rmChildren() throws KeeperException, InterruptException {
//byte[] data = zkCli.getData("/bbq", true, null);
//不能删除节点中的数据,不能存在空节点
zkCli.delete("/bbq", -1);//-1是删除所有版本
}
//修改数据
public void setData() throws KeeperException, InterruptException {
zkCli.setData("/terry", "17".getBytes(), -1);
}
//判断节点是否存在
public void testExist() throws KeeperException, InterruptException {
Stat exists = zkCli.exists("/terry", true);
System.out.println(exists == null ? "not exists" : "exists");
}
}
}