zookeeper的节点类型
- PERSISTENT 持久化节点
- PERSISTENT_SEQUENTIAL 持久化顺序节点 节点编号是唯一的
- EPHEMERAL 临时节点
- EPHEMERAL_SEQUENTIAL 临时节点带顺序 节点编号唯一
持久化的节点,client断开也会永久保存。临时节点会随着client的端口删除。
client的初始化
public static ZooKeeper getZookeeperConn(String address) throws IOException {
String connectString = address;
int sessionTimeout = 3000; // 会话超时时间
System.out.println("zookeeper connecting 。。。。。。");
ZooKeeper zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
// 监听器
@Override
public void process(WatchedEvent event) {
System.out.println("事件被触发了 --- {" + event.getState() + "} ---, 在这里我们可以做一些事情!!!");
}
});
System.out.println("zookeeper connection success!");
return zooKeeper;
}
测试方法
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ZooKeeper zooKeeper=ZkApi.getZookeeperConn("127.0.0.1:2181");
Thread.sleep(10000);//这里需要等一段时间 否则会异常
zooKeeper.create("/test", "test node".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
// Stat stat=zooKeeper.exists("/blf",false);
List<String> nodeList=zooKeeper.getChildren("/",false);
for (String path:nodeList){
System.out.println(path);
}
}