【基于zookeeper 客户端的Curator API 基本操作】

pom依赖
 <!-- zookeeper -->
    <dependency>
        <groupId>org.apache.zookeeper</groupId>
        <artifactId>zookeeper</artifactId>
        <version>3.4.9</version>
    </dependency>
    <!-- zk 客户端api-->
    <dependency>
        <groupId>org.apache.curator</groupId>
        <artifactId>curator-recipes</artifactId>
        <version>4.0.1</version>
    </dependency>
组件
  • curator-framework:对zookeeper的底层api的一些封装
  • curator-client:提供一些客户端的操作,例如重试策略等
  • curator-recipes:封装了一些高级特性,如:Cache事件监听、选举、分布式锁、分布式计数器、分布式Barrier等
基本操作
  1. create() 创建节点
  2. getData() 获取节点
  3. getChildren() 获取子节点信息
  4. NodeCache 注册监听 监听节点值变更(重复监听)
  5. PathChildrenCache 注册子节点监听(重复监听)
  6. TreeCache 注册监听,监听节点及子节点的变更 (重复监听)
package com.zzhijian.zookeeperdemo.zk;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.cache.*;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.*;

import java.util.List;

/**
 * TODO:
 *
 * @author 
 * @date: 2019-08-15 15:07
 **/
@Slf4j
public class CuratorApiDemo {

    private static String ZK_ADDRESS = "zkServer:2181,zkServer:2182,zkServer:2183";
    private static Integer SESSION_TIME_OUT_MS = 1000*10;
    private static Integer CONNECTION_TIME_OUT_MS = 1000*10*6;
    private static ZooKeeper zooKeeper;
    private static CuratorFramework curatorFramework;

    public static void main(String[] args) throws Exception{
        // 初始化客户端
       /* initClient();
        createNode();*/
        init();
        //createNode01();
        //getNodeValue();
        //setNodeValue();
        //getNodeChildren();
        // 一次监听
        getNodeChildCuratorListener();
        //重复监听
        watchNodeCache();
        watchChildNodeCache();
        watchTreeNodeCache();
        Thread.sleep(1000* 60*10);
    }
    /**
     * TODO: 初始化zk客户端
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午3:40
     */
    public static void initClient() throws Exception{
        // 提供了重试策略
        CuratorZookeeperClient curatorZookeeperClient = new CuratorZookeeperClient(ZK_ADDRESS, SESSION_TIME_OUT_MS, CONNECTION_TIME_OUT_MS, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                log.error("事件被触发了 --- 连接状态:{},事件:{} ---, 在这里我们可以做一些事情!!!",event.getState(),event.getType());
            }
        },new RetryNTimes(3,1000));
        curatorZookeeperClient.start();
        zooKeeper = curatorZookeeperClient.getZooKeeper();
    }

    public static void createNode() throws Exception{
        //zooKeeper.create("/curator-test", "node".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
        zooKeeper.create("/curator-02", "node".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
        zooKeeper.create("/curator-02/01", "node".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
    }
    /**
     * TODO: 初始化
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午4:06
     */
    public static void init(){
        //实例化客户端
        curatorFramework = CuratorFrameworkFactory.builder()
                .connectString(ZK_ADDRESS)
                .connectionTimeoutMs(CONNECTION_TIME_OUT_MS)
                .sessionTimeoutMs(SESSION_TIME_OUT_MS)
                .retryPolicy(new RetryNTimes(3,1000))
                .build();
        // 启动客户端
        curatorFramework.start();
    }
    /**
     * TODO: 创建节点
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午5:19
     */
    public static void createNode01(){
        try {
            curatorFramework.create()
                    .forPath("/curator06/0601");
            // acl 权限 mode 节点类型 递归创建节点
            curatorFramework.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.EPHEMERAL)
                    .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                    .forPath("/curator07/curator0701"," 测试递归节点内容".getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * TODO: 获取节点信息
     * @param
     * @author 
     * @return java.lang.String
     * @version  1.0
     * @date 2019/8/15  下午5:20
     */
    public static void getNodeValue() {
        try {
            log.error(new String(curatorFramework.getData().forPath("/curator0601")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * TODO: 获取子节点列表(usingWatcher 一次性监听)
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午5:24
     */
    public static void getNodeChildren() throws Exception{
        List<String> list = curatorFramework
                .getChildren()
                .usingWatcher(new CuratorWatcher() {
                    @Override
                    public void process(WatchedEvent watchedEvent) {
                        log.error("节点列表事件触发了 --- 连接状态:{},事件:{} ---, 在这里我们可以做一些事情!!!",watchedEvent.getState(),watchedEvent.getType());
                    }
                })
               /* .usingWatcher(new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        log.error("节点列表事件触发了 --- 连接状态:{},事件:{} ---, 在这里我们可以做一些事情!!!",event.getState(),event.getType());
                    }
                })*/
                .forPath("/curator06");
        log.error(list.toString());
    }

    /**
     * TODO: 获取节点信息
     * @param
     * @author 
     * @return java.lang.String
     * @version  1.0
     * @date 2019/8/15  下午5:20
     */
    public static void setNodeValue() {
        try {
            log.error(String.valueOf(curatorFramework
                    .setData()
                    .forPath("/curator07","修改节点信息".getBytes())));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * TODO: 获取子节点列表(CuratorListener 一次性监听)
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/15  下午5:24
     */
    public static void getNodeChildCuratorListener() throws  Exception{
        // 注册一个监听器
        CuratorListener listener = new CuratorListener() {
            @Override
            public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
                System.out.println("监听事件触发,event内容为:" + event);
            }
        };
        curatorFramework.getCuratorListenable().addListener(listener);
        // 获取节点列表
        curatorFramework
                .getChildren()
                .inBackground()
                .forPath("/curator06");
    }
    /**
     * TODO: 监听节点内容的变化
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/16  上午9:40
     */
    public static void watchNodeCache() throws Exception{
        // 创建nodeCache对象
        NodeCache nodeCache = new NodeCache(curatorFramework,"/curator06");
        // 启动缓存
        nodeCache.start();
        if(nodeCache.getCurrentData() != null){
            log.error("节点的初始化数据为:"+new String(nodeCache.getCurrentData().getData()));
        }else{
            log.error("节点初始化数据为空。。。");
        }
       nodeCache.getListenable().addListener(new NodeCacheListener() {
           @Override
           public void nodeChanged() throws Exception {
               String data = new String(nodeCache.getCurrentData().getData());
               log.error("watchNodeCache-监听节点变更---{}",data);
           }

       });
    }
    /**
     * TODO: 监听子节点变更
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/16  下午4:55
     */
    public static void watchChildNodeCache() throws Exception{
        // PathChildrenCache 对象
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFramework,"/curator06",true);
        // 启动缓存
        pathChildrenCache.start();
        // 增加监听
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                log.error("watchChildNodeCache-监听节点变更---{}",pathChildrenCache.getCurrentData());
            }
        });
    }
    /**
     * TODO: 监听tree节点变更
     * @param
     * @author 
     * @return void
     * @version  1.0
     * @date 2019/8/16  下午5:21
     */
    public static void watchTreeNodeCache() throws Exception{
        // 创建nodeCache对象
        TreeCache treeCache = new TreeCache(curatorFramework,"/curator06");
        // 启动缓存
        treeCache.start();
        // 增加监听
        treeCache.getListenable().addListener(new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                log.error("watchTreeNodeCache-监听节点变更---{},{}",treeCache.getCurrentChildren("/curator06"),treeCache.getCurrentData("/curator06"));
            }
        });
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值