ZooKeeper完全解析(八) 使用Curator来简化ZooKeeper操作之基本使用

  在前几篇中,我们讲解了如何使用 Java ZooKeeper 库来操作ZooKeeper,但是 Java ZooKeeper 库只实现了ZooKeeper的一些基本操作,其余分布式锁,群首选举等等,都没有给出解决方法,那么有没有这么一个库来实现这些方案呢???答案是肯定的,就是我们今天要讲的Curator。

一、引入Curator:

  curator有很多模块,核心的模块为
    curator-framework

  跟Spring-framowork-core类似,其它的模块有curator-client、curator-async等等,而我们只需要引入一个  
    curator-recipes 

  模块即可,curator-recipes 里面包含了其它模块。

  因为我们的zooKeeper是 3.4.13 版本,所以  curator-recipes  也要使用 2.x.x 版本,如果使用更高版本会出现 
org.apache.zookeeper.KeeperException$UnimplementedException: KeeperErrorCode = Unimplemented for...
  错误

所以我的引入为:
        <!-- curator -->
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.12.0</version>
        </dependency>

二、Curator中的增删查改与时间监听:

  ZooKeeper中的增删查改,分别对应create、delete、(get,ls2,state)、set命令,那么用Curator实现的代码为:

 1、连接ZooKeeper:

    // 重试策略
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFramework client = CuratorFrameworkFactory.newClient(env.getProperty("zookeeper.url"), retryPolicy);
    client.start();

 2、create:

    // 增加,对应命令  create
    client.create().withMode(CreateMode.PERSISTENT).forPath(curatorPath, "curator_data".getBytes());

 3、delete:

    // 删
    client.delete().forPath(curatorPath + "/" + childList.get(0));
    List<String> childAfterList = client.getChildren().forPath(curatorPath);
    System.out.println(JSON.toJSONString("after : " + childAfterList));

 4、get与stat以及其时间监听:

    // 监听
    client.getData().usingWatcher((CuratorWatcher) e->{
                    if (e.getType() == Watcher.Event.EventType.NodeDataChanged) {
                        System.out.println("监听数据更新  节点数据更新");
                    } else if (e.getType() == Watcher.Event.EventType.NodeDeleted) {
                        System.out.println("监听数据更新  节点被删除");
                    }
    }).forPath(curatorPath);
    client.getChildren().usingWatcher((CuratorWatcher) e->{
                    if (e.getType() == Watcher.Event.EventType.NodeChildrenChanged) {
                        System.out.println("监听子节点更新  节点数据更新");
                    } 
    }).forPath(curatorPath);

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值