其他分享
首页 > 其他分享> > zookeeperAPI及示意图

zookeeperAPI及示意图

作者:互联网

代码

public class zookeeperAPI {
    /**
     * 连接Zookeeper
     * bigdata111  主机名(虚拟机)
     * 2181  端口号
     * */
    private static String connectzk = "bigdata111:2181";

    //时间 (毫秒)
    private static int seeionTimeOut = 2000;

    //创建客户端
    private static ZooKeeper zkClient = null;

    //运行
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        init();
//        createznode();
//        exist();
//        get();
    }
    //初始化
    private static void init() throws IOException {
        zkClient = new ZooKeeper(connectzk, seeionTimeOut, new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                //收到事件通知
                /**
                 * watchedEvent.getType() 监听类型
                 * watchedEvent.getPath() 监听路径
                 * */
                System.out.println(watchedEvent.getType() + "--" + watchedEvent.getPath());
                //再次启动监听器
                try {
                    //监听路径 true开启
                    zkClient.getChildren("/",true);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }
    //创建znode节点
    public static void createznode() throws KeeperException, InterruptedException {
        /**
         *znode路径
         *znode数据
         *znode权限
         * znode类型:持久,临时,持久有序,临时有序
         * */
        String znode = zkClient.create("/idea", "hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(znode);

    }
    //判断节点是否存在
    public static void exist() throws KeeperException, InterruptedException {

        //"/idea"  要判断的文件
        Stat exists = zkClient.exists("/idea", true);

        //"not exist" 不存在  "exist" 存在
        System.out.println(exists==null?"not exist":"exist");
    }
    //获取子节点
    public static void get() throws KeeperException, InterruptedException {

        //"/" 路径下子节点
        List<String> children = zkClient.getChildren("/", true);

        // 使用增强for打印
        for (String znode : children){
            System.out.println(znode);
        }
    }

}

0

现在我的zookeeper客户端只有一个zookeeper

1

运行createznode方法

2

zookeeper客户端现在就有 idea 这个znode节点了

3

运行exist方法查看 idea 这个znode节点是否存在

4

获取 / 节点的值

在这里插入图片描述

标签:zookeeperAPI,public,exist,zkClient,static,znode,void,示意图
来源: https://blog.csdn.net/csdnwindnorth/article/details/100564886