首页 > 其他分享 >Zookeeper原生客户端操作

Zookeeper原生客户端操作

时间:2023-02-22 22:56:34浏览次数:40  
标签:原生 String Zookeeper System println path 节点 客户端

在Linux系统中安装了Zookeeper服务器,对Zookeeper命令有一些了解的情况下,学习如何在客户端操作Zookeeper。目前,Zookeeper服务器有三种Java客户端: Zookeeper、Zkclient和Curator

Zookeeper: Zookeeper是官方提供的原生java客户端(官方)
Zkclient: 是在原生zookeeper客户端基础上进行扩展的开源第三方Java客户端
Curator: Netflix公司在原生zookeeper客户端基础上开源的第三方Java客户端

3.1 Zookeeper客户端

在接下来的学习中,主要是使用Zookeeper3.7.1版本来演示客户端操作,依赖引入:

<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.7.1</version>
</dependency>

3.1.1 创建客户端连接Create

public class ZookeeperUtils {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    public static void init(String connection,int timeout){
        try{
            ZooKeeper zooKeeper = new ZooKeeper(connection,timeout,watcher -> {
                //获取监听事件状态
                Watcher.Event.KeeperState state = watcher.getState();
                //获取事件类型
                Watcher.Event.EventType type = watcher.getType();

                //如果连接已经建立
                if(Watcher.Event.KeeperState.SyncConnected == state){
                    if(Watcher.Event.EventType.None == type){
                        System.out.println("ZooKeeper连接已经建立");
                        countDownLatch.countDown();
                    }
                }
                
                if(Watcher.Event.EventType.NodeCreated == type){
                    System.out.println("Zookeeper有新的节点" + watcher.getPath() + "创建");
                }

                if(Watcher.Event.EventType.NodeDataChanged == type){
                    System.out.println("Zookeeper节点" + watcher.getPath() + "中数据已经发生变化");
                }

                if(Watcher.Event.EventType.NodeDeleted == type){
                    System.out.println("Zookeeper节点" + watcher.getPath() + "被删除");
                }

                if(Watcher.Event.EventType.NodeChildrenChanged == type){
                    System.out.println("Zookeeper节点" + watcher.getPath() + "的子节点已经发生变化");
                }
            });
            //必须等Zookeeper连接成功之后才能进行后续操作,否则一直等待
            countDownLatch.await();
            System.out.println("init connection success " + zooKeeper);

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

CountDownLatch是一个同步工具类,用来协调多个线程之间的同步,或者说起到线程之间的通信(而不是用作互斥的作用)。CountDownLatch能够使一个线程在等待另外一些线程完成各自工作之后,再继续执行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后,计数器的值就会减一。当计数器的值为0时,表示所有的线程都已经完成一些任务,然后在CountDownLatch上等待的线程就可以恢复执行接下来的任务。

3.1.2 创建节点Node

	/**
     * 根据路径和值创建Zookeeper节点
     * @param path
     * @param value
     */
    public static void createNode(String path,String value) throws InterruptedException, KeeperException {
        if("".equals(path)){
            System.out.println("节点路径不能为空");
            return;
        }

        ZooKeeper zooKeeper =  ZookeeperUtils.init("*.*.*.*:2181",60000);

        //如果路径已经存在不能创建
        if(zooKeeper.exists(path,false) != null){
            System.out.println("节点:" + path + "已经存在。不能创建");
            return;
        }

        String result = zooKeeper.create(path,value.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("Zookeeper已经创建路径为:" + path + ",值为:" + value + "的节点");
    }

    /**
     * 递归创建节点
     * @param path
     * @param value
     */
    public static void createNodeRecursion(String path,String value) throws InterruptedException, KeeperException {
        if("".equals(path)){
            System.out.println("创建节点的路径不能为空");
            return;
        }

        String[] paths = path.substring(1).split("/");
        for(int i = 0; i < paths.length; i++){
            String childPath = "";
            for(int j = 0; j <= i; j++){
                childPath += "/" + paths[j];
            }
            createNode(childPath,value);
        }
    }

3.1.3 查询节点

	/**
     * 根据路径查询节点
     * @param path
     */
    public static void queryNode(String path) throws InterruptedException, KeeperException {
        if("".equals(path)){
            System.out.println("查询节点的路径不能为空!");
            return;
        }
        ZooKeeper zooKeeper =  ZookeeperUtils.init("*.*.*.*:2181",60000);
        byte[] result = zooKeeper.getData(path,false,null);
        System.out.println(new String(result));

        Stat stat = new Stat();
        byte[] result1 = zooKeeper.getData(path,true,stat);
        System.out.println("节点:" + path + "的值为:" + new String(result1) + "Stat:" + stat);
    }

3.1.4 更新节点

public static void setData(String path,String value) throws InterruptedException, KeeperException {
        ZooKeeper zooKeeper =  ZookeeperUtils.init("*.*.*.*:2181",60000);
        zooKeeper.setData(path,value.getBytes(),-1);

    }

3.1.5删除节点

public static void deleteNode(String path) throws InterruptedException, KeeperException {
        ZooKeeper zooKeeper =  ZookeeperUtils.init("*.*.*.*:2181",60000);
        if(zooKeeper.exists(path,false) == null){
            System.out.println("要删除的节点不存在!");
        }
        zooKeeper.delete(path,-1);

    }

标签:原生,String,Zookeeper,System,println,path,节点,客户端
From: https://www.cnblogs.com/wyzstudy/p/17146314.html

相关文章