zookeeper系列(四)—客戶端API使用

zookeeper系列(四)—客戶端API使用

前言

大家好,牧碼心今天給大家推薦一篇zookeeper系列(四)—客戶端API使用的文章,在實際工作中有很多應用場景,希望對你有所幫助。內容如下:

  • 概要
  • 創建和關閉會話
  • 創建和查看節點
  • 修改和刪除節點
  • 設置權限
  • curator框架

概要

zookeeper提供了zkCli.sh腳本,通過命令交互方式調試zk集羣,但在項目開發中不推薦使用。zookeeper官方提供了java和C中語言的客戶端,實際開發時我們一般會使用相應的zookeeper API,或者使用封裝更高級的框架庫 Curator。
本文java客戶端爲例來實現創建會話,創建節點,監聽節點,刪除節點,獲取數據,設置權限,關閉會話等功能。

依賴

在使用zookeeper API之前,我們需要引入相關API的依賴,依賴方式如下,這裏以maven爲例:

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

這裏選擇的版本是3.5.5,更多版本選擇,詳見:https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper

創建和關閉會話

  • 創建會話
    啓動zookeeper服務端後,客戶端可通過構造函數 ZooKeeper()創建會話,實例化後將會自動與集羣建立連接。函數定義如下:
ZooKeeper(String connectionString, int sessionTimeout, Watcher watcher)

函數參數說明如下:

參數名稱 類型 說明
connectString String 連接串,包括ip+端口 ,集羣模式下用逗號隔開 hadoop01:2181,hadoop02:2181,hadoop03:2181
sessionTimeout int 會話超時時間,該值不能超過服務端所設置的 minSessionTimeout 和maxSessionTimeout
watcher Watcher 會話監聽器,服務端事件將會觸該監聽

示例代碼:

private ZooKeeper zooKeeper;
final CountDownLatch connectedSignal = new CountDownLatch(1);
public ZooKeeper connect(String host) throws IOException,InterruptedException {
      zooKeeper= new ZooKeeper(host,5000,new Watcher() {
      // 定義監聽事件
         public void process(WatchedEvent we) {
            if (we.getState() == KeeperState.SyncConnected) {
               connectedSignal.countDown();
            }
         }
      });
      connectedSignal.await();
      return zooKeeper;
   }
  • 關閉會話
    關閉會話比較簡單,zookeeper提供了close()函數來關閉會話,示例代碼在此省略

創建和查看節點

  • 創建節點
    zookeeper提供了create()函數來創建新節點,函數定義如下:
String create(final String path, byte data[], List<ACL> acl,CreateMode createMode)

具體參數說明如下:

參數名稱 類型 說明
path String 節點路徑,如/myApp、/myApp/data
data byte[] 節點賦值
acl List 節點訪問權限,zookeeper提供了一個接口定義權限,如ZooDefs.Ids下的屬性
createMode CreateMode 創建的節點類型,是一個枚舉類 CreateMode

示例代碼:

public void createData() throws KeeperException, InterruptedException {
       List<ACL> list = new ArrayList<>();
       int perm = ZooDefs.Perms.ADMIN | ZooDefs.Perms.READ;//cdwra
       ACL acl = new ACL(perm, new Id("world", "anyone"));
       ACL acl2= new ACL(perm, new Id("ip", "127.0.0.1"));
       list.add(acl);
       list.add(acl2);
       zooKeeper.create("/myApp/data", "hello".getBytes(), list, CreateMode.PERSISTENT);
   }
  • 查看節點
    zookeeper提供了getData()可查看節點和數據,函數定義如下:
getData(String path, Watcher watcher, Stat stat)

函數參數說明如下:

參數名稱 類型 說明
path String 節點路徑,如/myApp、/myApp/data
watch Watcher 會話監聽器,服務端事件將會觸該監聽
stat Stat 節點元數據

示例代碼:

public void getData() throws KeeperException, InterruptedException {
        Stat stat = new Stat();
        zooKeeper.getData("/myApp/data", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                try {
                    zooKeeper.getData(event.getPath(), this, null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(event.getPath());
            }
        }, stat);
        System.out.println(stat);
        Thread.sleep(Long.MAX_VALUE);
    }
  • 查看子節點
    zookeeper提供了getChildren()獲取子節點,函數定義如下:
List<String> getChildren(final String path, Watcher watcher)

函數參數說明如下:

參數名稱 類型 說明
path String 節點路徑,如/myApp、/myApp/data
watcher Watcher 會話監聽器,服務端事件將會觸該監聽,如boolean watcher 是true,則會使用

示例代碼:

 public void getChild() throws KeeperException, InterruptedException {
        List<String> children = zooKeeper.getChildren("/myApp", event -> {
            System.out.println(event.getPath());
            try {
                zooKeeper.getChildren(event.getPath(), false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        children.stream().forEach(System.out::println);
        Thread.sleep(Long.MAX_VALUE);
    }

修改和刪除節點

  • 修改節點
    zookeeper提供了setData()函數來設置節點權限,函數定義如下:
setData(String path, byte[] data, int version)

函數參數說明如下:

參數名稱 類型 說明
path String 節點路徑,如/myApp、/myApp/data
data byte[] 節點修改的數據
version int 節點當前的版本號

示例代碼

public  void updateTest() throws
      KeeperException,InterruptedException {
      String path= "/myApp";
      byte[] data = "Success".getBytes(); 
      zookeeper.setData(path, data, zookeeper.exists(path,true).getVersion());
   }
  • 刪除節點
    zookeeper提供了setData()函數來設置節點權限,函數定義如下:
delete(String path, int version)

函數參數說明如下:

參數名稱 類型 說明
path String 節點路徑,如/myApp、/myApp/data
version int 節點當前的版本號

示例代碼

public  void deleteTest() throws
      KeeperException,InterruptedException {
      String path= "/myApp";
      zookeeper.delete(path, zookeeper.exists(path,true).getVersion());
   }

設置權限

zookeeper提供了setAcl()函數來設置節點權限,ACL權限結構爲scheme🆔permission,具體的可參考中zookeeper系列(三)—節點詳解的ACL的說明,函數定義如下:

setACL(final String path, List<ACL> acl, int aclVersion)

函數參數說明如下:

參數名稱 類型 說明
path String 節點路徑,如/myApp、/myApp/data
acl List 節點訪問權限,zookeeper提供了一個接口定義權限,如ZooDefs.Ids下的屬性
aclVersion int 節點權限版本號

示例代碼:

public void setAclTest() throws KeeperException, InterruptedException {
        List<ACL> aclList = new ArrayList<>();
        int perm = ZooDefs.Perms.ADMIN | ZooDefs.Perms.READ|ZooDefs.Perms.WRITE;
        aclList.add(new ACL(perm, new Id("world", "anyone")));
        aclList.add(new ACL(ZooDefs.Perms.ALL, new Id("ip", "127.0.0.1")));
        zooKeeper.setACL("/myApp", aclList, 5);
    }

Curator框架

Curator是Netflix公司開源的一套zookeeper客戶端框架,解決了很多Zookeeper客戶端非常底層的細節開發工作,包括連接重連、反覆註冊Watcher和NodeExistsException異常等。Curator包含了幾個包:

1、curator-framework:對zookeeper的底層api的一些封裝;
2、curator-client:提供一些客戶端的操作,例如重試策略等;
3、curator-recipes:封裝了一些高級特性,如:Cache事件監聽、選舉、分佈式鎖、分佈式計數器、分佈式Barrier等

Maven依賴(使用curator的版本:4.3.0,對應Zookeeper的版本爲:3.5.x,如果跨版本會有兼容性問題,很有可能導致節點操作失敗):依賴方式見:https://mvnrepository.com/artifact/org.apache.curator/curator-client/4.3.0

  • 關於Curator框架使用可參考:http://curator.apache.org/getting-started.html

參考

  • https://www.tutorialspoint.com/zookeeper/zookeeper_api.htm
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章