Fundamentals of ZooKeeper API
The application that interacts with the ZooKeeper collection is called the ZooKeeper client or simply the client. Znode is the core component of the ZooKeeper set. The ZooKeeper API provides a small group of methods to use the ZooKeeper set to manipulate all the details of znode.
The client should follow the steps to have clear and clean interaction with the ZooKeeper collection.
- Connect to the ZooKeeper collection. The ZooKeeper collection assigns a session ID to the client.
- Send heartbeat to the server regularly. Otherwise, the ZooKeeper collection will expire the session ID and the client needs to reconnect.
- znode can be obtained / set as long as the session ID is active.
- After all tasks are completed, disconnect from the ZooKeeper collection. If the client is inactive for a long time, the ZooKeeper collection will automatically disconnect the client.
The core part of the ZooKeeper API is the ZooKeeper class
The most important set of ZooKeeper APIs in this chapter. The core part of the ZooKeeper API is the ZooKeeper class. It provides the option to connect the ZooKeeper collection in its constructor and has the following methods:
- Connect - connect to the ZooKeeper collection
- Create - create znode
- Exists - check whether znode exists and its information
- getData - get data from a specific znode
- setData - set data in a specific znode
- getChildren - gets all child nodes in a specific znode
- delete - deletes a specific znode and all its children
- Close - close the connection
maven, lead me
<dependencies> <!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper --> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.14</version> <type>pom</type> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.curator/curator-framework --> <!--<dependency> <groupId>org.apache.curator</groupId> <artifactId>curator-framework</artifactId> <version>4.2.0</version> </dependency> --> </dependencies>
1. Construct Chuang FA to establish connection
The ZooKeeper class provides the connect function through its various constructors. As follows: ZooKeeper(String connectionString, int sessionTimeout, Watcher watcher)
- connectionString - ZooKeeper collection hosts. Multiple hosts are separated by commas. eg:"ip1:2181,ip2:2181,ip3:2181".
- sessionTimeout - session timeout in milliseconds.
- watcher - an object that implements the monitor interface. The ZooKeeper collection returns the connection status through the monitor object.
Here, a count is made by using the watcher and countDownLatch. The main thread is blocked until the connection is connected and the counter countDownLatch is decremented. The current connection status is printed only after the connection is established successfully
private static void getZkConection() { CountDownLatch countDownLatch=new CountDownLatch(1); String connection="ip:port"; try { zooKeeper=new ZooKeeper(connection, 4000, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { if (watchedEvent.getState()==Event.KeeperState.SyncConnected){ countDownLatch.countDown(); } } }); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void closeZkConnection(){ try { zooKeeper.close(); } catch (InterruptedException e) { e.printStackTrace(); } }
Addition, deletion, modification and query of Zookeeper
1.create -- create Znode
The ZooKeeper class provides a create method to create a new znode in the ZooKeeper collection. The signature of the Create method is as follows: create(String path, byte[] data, List<ACL> acl, CreateMode createMode)
- path - Znode path. For example, / myapp1, / myapp2, / myapp1/mydata1
- Data - data to be stored in the specified znode path
- acl - access control list for the node to be created. The ZooKeeper API provides a static interface zoodefs IDS to get some basic acl lists. For example, zoodefs Ids. OPEN_ acl_ Unsafe returns the acl list of the open znode.
- createMode - the type of node, i.e. temporary, sequential, persistent, etc. This is an enumeration.
private static void createZkMode() { try { zooKeeper.create("/test2", "JavaApiTest".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }

result
2 . Exists -- check the existence of Znode and return a node information stat
The ZooKeeper class provides the exists method to check the existence of znode. If the specified znode exists, the metadata of a znode is returned. The exists method is signed as follows: exists(String path, boolean watcher)
- path- Znode path
- exists(String path, boolean watcher) watcher - Boolean value that specifies whether to monitor the specified znode
private static void checkZnode(String s) { try { Stat stat = zooKeeper.exists(s, true); if (stat==null){ System.out.println("Node is empty"); }else { System.out.println("Node exists,And the version of the current node is:"+stat.getVersion()+"Created on:"+stat.getCtime()); } } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }

result
3 . getData method -- get the data value and node information stat
The ooKeeper class provides a getData method to obtain the data attached to the specified znode and its status. The signature of the getData method is as follows: getData(String path, Watcher watcher, Stat stat)
- path - Znode path.
- watcher - callback function of monitor type. When the data of the specified znode changes, the ZooKeeper collection will be notified through the monitor callback. This is a one-time notice. [nullable]
- stat - returns the metadata of znode. [nullable]
private static void getZnodeData(String path) { try { byte[] data = zooKeeper.getData(path, null, null); System.out.print("The node value is"+new String(data)); } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }

setData -- change node value
The ZooKeeper class provides the setData method to modify the attached data in the specified znode, and can also return a modified stat value. The signature of the setData method is as follows: setData(String path, byte[] data, int version)
- path- Znode path
- Data - the data to be stored in the specified znode path.
- Version - the current version of znode. Whenever the data changes, ZooKeeper updates the version number of znode.
private static void setZnode(String path) { try { Stat stat = zooKeeper.exists(path, false); if (stat==null){ System.out.println("Znode does not exist"); }else { System.out.println("The old version is"+stat.getVersion()); Stat newStat = zooKeeper.setData(path, "newValue".getBytes(), stat.getVersion()); System.out.println("The new version is"+newStat.getVersion()); getZnodeData(path); } } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }

Delete -- delete Znode
delete(String path, int version)
- path - Znode path.
- Version - the current version of znode
private static void deleteZnode(String path) { try { Stat stat = zooKeeper.exists(path, false); if (stat==null){ System.out.println("Znode does not exist"); }else { zooKeeper.delete(path,stat.getVersion()); } } catch (KeeperException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } }

The path passed is "test2, it's gone"
getChildren gets all child nodes of a specific znode
The ZooKeeper class provides a getChildren method to get all the child nodes of a specific znode. The signature of the getChildren method is as follows: getChildren(String path, Watcher watcher)
- path - Znode path.
- watcher - callback function of monitor type. When the specified znode is deleted or the child node under the znode is created / deleted, the ZooKeeper collection will notify. This is a one-time notice. [null able]
private static void getZnodeChild(String path) throws KeeperException, InterruptedException { Stat stat = zooKeeper.exists(path, null); if (stat==null){ System.out.println("Znode does not exist"); }else { List<String> list = zooKeeper.getChildren(path, null); for(int i=0;i<list.size();i++){ System.out.println(list.get(i)); } } }

