zookeeper原生API操作(创建删除查询更改)zookeeper实战

目前主流有三种方法去操作zookeeper节点,即zookeeper shell、zookeeper原生API、apache curator API(在原生基础上封装,更加友好易用)。本文主要是基于zookeeper原生API来创建删除查询更改zookeeper节点。

注意事项:

  • 原生zookeeper api创建某个节点,必须保证父节点已经存在,否则不能创建(即不能递归创建节点)
  • 原生zookeeper api删除某个节点,如果该节点中还有子节点,则该父节点不能直接删除,而必须先删除所有子节点(即不能递归删除节点)

pom中添加如下依赖:

        <!-- 如果代码中不使用hadoop 的Configuration,则不需要添加hadoop-common依赖 -->
        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.6.0-cdh5.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.6</version>
        </dependency>

java详细代码:


package com.example.zkaccess;

import org.apache.hadoop.conf.Configuration;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

public class TestZk {
    
    // 初始化zookeeper client
    public ZooKeeper initZooKeeper(Configuration conf) {
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper(conf.get("ha.zookeeper.quorum"), 3000, new Watcher() {
            // conf.get("ha.zookeeper.quorum"): 读取hadoop配置项zookeeper quorum,即常说的connectstring
            // 可以配置在core-site.xml中,比如127.0.0.1:2181, 100.11.12.1:2181
            // 3000指timeout为3s
                @Override
                public void process(WatchedEvent event) {
                    System.out.println(event.toString());
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        return zooKeeper;
    }


     // 创建父节点
     private void createParentNode(ZooKeeper client, String path) throws KeeperException, InterruptedException {
        String newPath = path;
        // 删除节点路径首尾的/符号
        if(path.startsWith("/")){
            newPath = newPath.substring(1);
        }
        if(path.endsWith("/")){
            newPath = newPath.substring(0,newPath.length()-1);
        }
         System.out.println(">>>>>> newPath is: " + newPath);
        String[] pathSplitArr = newPath.split("/");
        String subPath = "";
        // 逐级创建节点,pathSplitArr.length-1级(第pathSplitArr.length级是seq-node,这里不创建)
        for(int i=0;i<pathSplitArr.length-1;i++){
            subPath = String.format("%s/%s", subPath, pathSplitArr[i]);
            System.out.println(subPath);
            if(client.exists(subPath,false)==null) {
                // 判断节点是否已经存在,null指不存在,不存在才能创建
                client.create(subPath, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                // 参数1:节点路径,参数2:节点数据,参数3:acl,参数4:节点类型
            }
        }
     }



    // 创建seq-node
    public void createSeqNode(ZooKeeper client, String path) throws KeeperException, InterruptedException {
        // 创建String path最后一级的父节点,比如path是"/ns-1/tenant/mysql1/seq-",那么此处的父节点就是:ns-1、tenant、mysql1
        createParentNode(client, path);
        // 节点路径必须以“/”开始且不以“/”结束
        String newPath = path;
        if(!path.startsWith("/")){
            newPath = "/".concat(newPath);
        }
        if(path.endsWith("/")){
            newPath = newPath.substring(0, newPath.length()-1);
        }
        if(client.exists(newPath, false) == null){
            // 创建顺序节点,比如"/ns-1/tenant/mysql1/seq-0000000000"
            client.create(newPath,"test".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        }
    }



     // 读取节点数据
     public byte[] getNodeData(ZooKeeper client, String path) throws KeeperException, InterruptedException {
         String newPath = path;
         byte[] data = null;
         if(!path.startsWith("/")){
             newPath = "/".concat(newPath);
         }
         if(path.endsWith("/")){
             newPath = newPath.substring(0, newPath.length()-1);
         }
         System.out.println(">>>>>> getNodeData newPath: " + newPath);       Stat stat = client.exists(newPath, false);
         System.out.println(stat==null ? ">>>>>> stat null":">>>>>> stat not null");
         if(stat != null){
             data = client.getData(newPath,false, stat);
         }
         return data;
     }



     // 修改节点数据
     public boolean setNodeData(ZooKeeper client, String path, byte[] data) {
        boolean finished = true;
         String newPath = path;
         if(!path.startsWith("/")){
             newPath = "/".concat(newPath);
         }
         if(path.endsWith("/")){
             newPath = newPath.substring(0, newPath.length()-1);
         }
        try {
             Stat stat = client.exists(newPath, false);
             // 节点存在才能够修改节点数据
             if( stat != null){
                 client.setData(newPath, data, stat.getVersion());
                 // 第3个参数:matched version,在此处为修改前的version,即stat.getVersion()
             }
         } catch (KeeperException e) {
             e.printStackTrace();
             finished = false;
         } catch (InterruptedException e) {
             e.printStackTrace();
             finished = false;
         }
         return finished;
     }


      // 删除节点
     public void deleteNode(ZooKeeper client, String path) throws KeeperException, InterruptedException {
         String newPath = path;
         if(!path.startsWith("/")){
             newPath = "/".concat(newPath);
         }
         if(path.endsWith("/")){
             newPath = newPath.substring(0, newPath.length()-1);
         }
        Stat stat = client.exists(newPath, false);
        // 先删除子节点
        if(stat != null){
            for(String node : client.getChildren(newPath, false)){
                // getChildren获取子节点名集合(不是全路径)
                System.out.println(">>>>>> node: " + node);
                Stat stat1 = client.exists(String.format("%s/%s", newPath, node),false);
                client.delete(String.format("%s/%s", newPath, node), stat1.getVersion());
            }
            // 再删除父节点
            client.delete(newPath, stat.getVersion());
        }
     }
     
}








package com.example.zkaccess;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Iterator;

/**
 * main类
 **/ 
public class TestMain {

    public static void main(String[] args) throws InterruptedException, KeeperException {

        // hadoop的配置类Configuration
        Configuration conf = new Configuration();
        String path = "/ns-1/tenant/mysql1/seq-/";
        String path1 = "/ns-1/tenant/mysql1/";
        TestZk testZk = new TestZk();
        // 初始化zookeeper client对象
        ZooKeeper zooKeeper = testZk.initZooKeeper(conf);
        // 创建顺序节点
        testZk.createSeqNode(zooKeeper, path1);
        System.out.println(new String(testZk.getNodeData(zooKeeper, path1), "UTF-8"));
        // 修改节点数据
        testZk.setNodeData(zooKeeper, path1, "test1".getBytes());
        System.out.println(new String(testZk.getNodeData(zooKeeper, path1), "UTF-8"));
        // 删除节点
        testZk.deleteNode(zooKeeper, path1);
        // 关闭zookeeper client
        zooKeeper.close();
    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,809评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,189评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,290评论 0 359
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,399评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,425评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,116评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,710评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,629评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,155评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,261评论 3 339
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,399评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,068评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,758评论 3 332
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,252评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,381评论 1 271
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,747评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,402评论 2 358