Zookeeper创建节点

zookeeper的节点类型

  1. PERSISTENT 持久化节点
  2. PERSISTENT_SEQUENTIAL 持久化顺序节点 节点编号是唯一的
  3. EPHEMERAL 临时节点
  4. 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);
        }
    }
    原文作者:我爱吻篮板
    原文地址: https://blog.csdn.net/qq_34796981/article/details/88685701
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞