zookeeperAPI及示意图

代码

public class zookeeperAPI {
    /**
     * 连接Zookeeper
     * bigdata111  主机名(虚拟机)
     * (如果要使用主机名的话,需要在window系统配置host。如果没有配置就得用创建虚拟机是设置的IP号)
     * 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);
        }
    }

}

依赖

6

0

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

1

运行createznode方法

2

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

3

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

4

获取 / 节点的值

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值