初步認識zookeeper(5)--Apache Curator操作節點(增刪改查)

目錄概要

  • 初始化連接
  • 增加節點
  • 查詢節點
  • 修改節點
  • 刪除節點

一、簡介
Apache Curator是一個比較完善的ZooKeeper客戶端框架,通過封裝的一套高級API 簡化了ZooKeeper的操作。通過查看官方文檔,可以發現Curator主要解決了三類問題:

  • 封裝ZooKeeper client與ZooKeeper server之間的連接處理
  • 提供了一套Fluent風格的操作API
  • 提供ZooKeeper各種應用場景(recipe, 比如:分佈式鎖服務、集羣領導選舉、共享計數器、緩存機制、分佈式隊列等)的抽象封裝

二、在pom.xml中添加如下依賴

 <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>3.4.10</version>
    </dependency>
    <dependency>
      <groupId>org.apache.curator</groupId>
      <artifactId>curator-framework</artifactId>
      <version>4.2.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.curator</groupId>
      <artifactId>curator-recipes</artifactId>
      <version>4.2.0</version>
    </dependency>

三、實操

1、初始化連接

CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().
                connectString("192.168.137.128:2181").
                sessionTimeoutMs(4000).retryPolicy(
                        new ExponentialBackoffRetry(1000,3)).
                build();
        curatorFramework.start();

2、添加節點

            //創建
            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).
                    forPath("/www", "xxx".getBytes());

3、查詢節點

            //查詢
            Stat stat = new Stat();
            byte[] bytes = curatorFramework.getData().storingStatIn(stat).forPath("/www");
            System.out.println("chauxn  "+new String(bytes));

4、修改節點

            //修改
            stat = curatorFramework.setData().withVersion(stat.getVersion()).forPath("/www", "gg".getBytes());

5、刪除節點

            //刪除
            curatorFramework.delete().deletingChildrenIfNeeded().forPath("/www");

6、關閉連接

curatorFramework.close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章