3、zookeeper在java使用的API

引入maven包

<dependency>
            <groupId>com.101tec</groupId>
            <artifactId>zkclient</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>zookeeper</artifactId>
                    <groupId>org.apache.zookeeper</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>log4j</artifactId>
                    <groupId>log4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
            <version>0.9</version>
        </dependency>
        <dependency>
            <artifactId>zookeeper</artifactId>
            <exclusions>
                <exclusion>
                    <artifactId>log4j</artifactId>
                    <groupId>log4j</groupId>
                </exclusion>
                <exclusion>
                    <artifactId>slf4j-log4j12</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
            <groupId>org.apache.zookeeper</groupId>
            <version>3.4.10</version>
        </dependency>
View Code

 

创建连接

Zookeeper(String connectionString, int sessionTimeout, watcher watcher)
  • connectionString - zookeeper主机

  • sessionTimeout- 会话超时

  • watcher - 实现"监听器" 对象。zookeeper集合通过监视器对象返回连接状态

public static void main(String[] args) throws IOException, InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);

        ZooKeeper zookeeper = new ZooKeeper("192.168.133.133:2181", 5000, (WatchedEvent x) -> {
            if (x.getState() == Watcher.Event.KeeperState.SyncConnected) {
                System.out.println("连接成功");
                countDownLatch.countDown();
            }
        });
        countDownLatch.await();
        System.out.println(zookeeper.getSessionId());
        zookeeper.close();
    }

 

新增节点
// 同步
  create(String path, byte[] data, List<ACL> acl, CreateMode createMode)
  // 异步
  create(String path, byte[] data, List<ACL> acl, CreateMode createMode,
        AsynCallback.StringCallback callBack, Object ctx)

 

 

  • 参数解释
    path znode路径
    data 数据
    acl 要创建的节点的访问控制列表。zookeeper API提供了一个静态接口 ZooDefs.Ids 来获取一些基本的acl列表。例如,ZooDefs.Ids.OPEN_ACL_UNSAFE返回打开znodeacl列表
    createMode 节点的类型,这是一个枚举
    callBack 异步回调接口
    ctx 传递上下文参数

示例:

// 枚举的方式
    public static void createTest1() throws Exception{
        String str = "node";
        String s = zookeeper.create("/node", str.getBytes(),
                ZooDefs.Ids.READ_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(s);
    }

  

 

修改节点

同样也有两种修改方式(异步和同步)

  • // 同步
    setData(String path, byte[] data, int version)
    // 异步
    setData(String path, byte[] data, int version, StatCallback callBack, Object ctx)
  •  

  • 参数解释
    path 节点路径
    data 数据
    version 数据的版本号, -1代表不使用版本号,乐观锁机制
    callBack 异步回调 AsyncCallback.StatCallback,和之前的回调方法参数不同,这个可以获取节点状态
    ctx 传递上下文参数
  •     public static void setData1() throws Exception{
      // arg1:节点的路径
           // arg2:修改的数据
           // arg3:数据的版本号 -1 代表版本号不参与更新
           Stat stat = zookeeper.setData("/hadoop","hadoop-1".getBytes(),-1);
      }
  •     public static void setData2() throws Exception{
           zookeeper.setData("/hadoop", "hadoop-1".getBytes(), 3 ,new AsyncCallback.StatCallback(){
               @Override
               public void processResult(int rc, String path, Object ctx, Stat stat) {
                   // 讲道理,要判空
                   System.out.println(rc + " " + path + " " + stat.getVersion() +  " " + ctx);
              }
          }, "I am context");
      }
删除节点

异步、同步

  • // 同步
    delete(String path, int version)
    // 异步
    delete(String path, int version, AsyncCallback.VoidCallback callBack, Object ctx)
  •  

  • 参数解释
    path 节点路径
    version 版本
    callBack 数据的版本号, -1代表不使用版本号,乐观锁机制
    ctx 传递上下文参数
  •     public static void deleteData1() throws Exception {
           zookeeper.delete("/hadoop", 1);
      }

       public static void deleteData2() throws Exception {
           zookeeper.delete("/hadoop", 1, new AsyncCallback.VoidCallback() {
               @Override
               public void processResult(int rc, String path, Object ctx) {
                   System.out.println(rc + " " + path + " " + ctx);
              }
          }, "I am context");
           TimeUnit.SECONDS.sleep(1);
      }

     

查看节点

同步、异步

  • // 同步
    getData(String path, boolean watch, Stat stat)
    getData(String path, Watcher watcher, Stat stat)
    // 异步
    getData(String path, boolean watch, DataCallback callBack, Object ctx)
    getData(String path, Watcher watcher, DataCallback callBack, Object ctx)
  •  

  • 参数解释
    path 节点路径
    boolean 是否使用连接对象中注册的监听器
    stat 元数据
    callBack 异步回调接口,可以获得状态和数据
    ctx 传递上下文参数
  •     public static void getData1() throws Exception {
           Stat stat = new Stat();
           byte[] data = zookeeper.getData("/hadoop", false, stat);
           System.out.println(new String(data));
           // 判空
           System.out.println(stat.getCtime());
      }

       public static void getData2() throws Exception {
           zookeeper.getData("/hadoop", false, new AsyncCallback.DataCallback() {
               @Override
               public void processResult(int rc, String path, Object ctx, byte[] bytes, Stat stat) {
                   // 判空
                   System.out.println(rc + " " + path
                                      + " " + ctx + " " + new String(bytes) + " " +
                                      stat.getCzxid());
              }
          }, "I am context");
           TimeUnit.SECONDS.sleep(3);
      }

     

查看子节点

同步、异步

  • // 同步
    getChildren(String path, boolean watch)
    getChildren(String path, Watcher watcher)
    getChildren(String path, boolean watch, Stat stat)    
    getChildren(String path, Watcher watcher, Stat stat)
    // 异步
    getChildren(String path, boolean watch, ChildrenCallback callBack, Object ctx)    
    getChildren(String path, Watcher watcher, ChildrenCallback callBack, Object ctx)
    getChildren(String path, Watcher watcher, Children2Callback callBack, Object ctx)    
    getChildren(String path, boolean watch, Children2Callback callBack, Object ctx)
  •  

  • 参数解释
    path 节点路径
    boolean  
    callBack 异步回调,可以获取节点列表
    ctx 传递上下文参数
  •     public static void getChildren_1() throws Exception{
           List<String> hadoop = zookeeper.getChildren("/hadoop", false);
           hadoop.forEach(System.out::println);
      }

       public static void getChildren_2() throws Exception {
           zookeeper.getChildren("/hadoop", false, new AsyncCallback.ChildrenCallback() {
               @Override
               public void processResult(int rc, String path, Object ctx, List<String> list) {
                   list.forEach(System.out::println);
                   System.out.println(rc + " " + path + " " + ctx);
              }
          }, "I am children");
           TimeUnit.SECONDS.sleep(3);
      }

 

检查节点是否存在

同步、异步

  • // 同步
    exists(String path, boolean watch)
    exists(String path, Watcher watcher)
    // 异步
    exists(String path, boolean watch, StatCallback cb, Object ctx)
    exists(String path, Watcher watcher, StatCallback cb, Object ctx)
  •  

  • 参数解释
    path 节点路径
    boolean  
    callBack 异步回调,可以获取节点列表
    ctx 传递上下文参数
  • public static void exists1() throws Exception{
       Stat exists = zookeeper.exists("/hadoopx", false);
       // 判空
       System.out.println(exists.getVersion() + "成功");
    }
    public static void exists2() throws Exception{
       zookeeper.exists("/hadoopx", false, new AsyncCallback.StatCallback() {
           @Override
           public void processResult(int rc, String path, Object ctx, Stat stat) {
               // 判空
               System.out.println(rc + " " + path + " " + ctx +" " + stat.getVersion());
          }
      }, "I am children");
       TimeUnit.SECONDS.sleep(1);
    }
  •  

posted @ 2021-04-01 10:32  低调人生  阅读(344)  评论(0编辑  收藏  举报