Article From:https://www.cnblogs.com/cxxjohnson/p/9121709.html

zookeeperAs a distributed service framework, it is mainly used to solve the problem of distributed data consistency. It provides API for many languages. This is the main record of the use of JAVA client API.

 

1.Creating a session

The client can connect to the zookeeper server by creating a ZooKeeper instance.

ZooKeeperThe 4 constructors are as follows:

 

[java] view plain copy

 
  1. ZooKeeper(connectString, sessionTimeout, watcher);  
  2. ZooKeeper(connectString, sessionTimeout, watcher,canBeReadOnly);  
  3. ZooKeeper(connectString, sessionTimeout, watcher, sessionId, sessionPasswd);  
  4. ZooKeeper(connectString, sessionTimeout, watcher, sessionId, sessionPasswd, canBeReadOnly);  

 

 

Parameter Description:

connectString: Connection strings, such as “127.0.0.1:2181”

sessionTimeout: The session timeout time is integer value in milliseconds. During sessionTimeout time, there is no effective heartbeat detection on the server side and the client side.

watcher: Default event notification processor

sessionId: Session ID

sessionPasswd: session key

canBeReadOnly: Is it a read only

      

[java] view plain copy

 
  1. public class ZookeeperSampleTest implements Watcher {  
  2.   
  3.     private static CountDownLatch connectedSemaphore = new CountDownLatch(1);  
  4.       
  5.     public static void main(String args[]) throws IOException, InterruptedException{  
  6.         ZooKeeper zk = new ZooKeeper(“192.168.1.138:2181”,5000,new ZookeeperSampleTest());  
  7.         System.out.println(zk.getState());  
  8.         try {  
  9.             connectedSemaphore.await();  
  10.         } catch (Exception e) {  
  11.             // TODO: handle exception  
  12.         }  
  13.         Long sessionId = zk.getSessionId();  
  14.         byte[] password = zk.getSessionPasswd();  
  15.         zk = new ZooKeeper(“192.168.1.138:2181”,5000,new ZookeeperSampleTest(),1L,“test”.getBytes());  
  16.         zk = new ZooKeeper(“192.168.1.138:2181”,5000,new ZookeeperSampleTest(),sessionId,password);  
  17.         Thread.sleep(Integer.MAX_VALUE);  
  18.         //System.out.println(“ZooKeeper session established”);  
  19.     }  
  20.   
  21.     @Override  
  22.     public void process(WatchedEvent event) {  
  23.         // TODO Auto-generated method stub  
  24.         System.out.println(“Receive watched event :” + event);  
  25.         if(event.getState()==KeeperState.SyncConnected){  
  26.             connectedSemaphore.countDown();  
  27.         }  
  28.     }  
  29.   
  30. }  

 

 

2.Create a node

The way to create nodes is divided into synchronous and asynchronous, and the constructor is as follows:

 

[java] view plain copy

 
  1. zk.create(path, data, acl, createMode);  
  2. , data, acl, createMode, cb, ctx);  

Parameter Description:

 

path: The path to create a node, such as: /zk-test

data[]: Byte array, node data

acl: Permissions

createMode: There are 4 types of node types: persistent nodes, persistent ordered nodes, temporary nodes, and temporary ordered nodes.

cb: The callback function needs to implement the StringCallback interface

ctx: Context is generally used when a callback function is used

 

[java] view plain copy

 
  1. public class ZookeeperSampleCreateTest implements Watcher {  
  2.   
  3.     public static CountDownLatch connectedSemaphore = new CountDownLatch(1);  
  4.       
  5.     public static void main(String[] args) throws IOException, InterruptedException, KeeperException{  
  6.         ZooKeeper zk = new ZooKeeper(“192.168.1.138:2181”,5000,new ZookeeperSampleCreateTest());  
  7.         connectedSemaphore.await();  
  8.         /*Sync
  9.         /*String path1 = zk.create(“/zk-test-ephemeral-“, “test-ephemeral”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 
  10.         System.out.println(“Success create node :” + path1); 
  11.         String path2 = zk.create(“/zk-test-ephemeral-“, “test-ephemeral-sequential”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); 
  12.         System.out.println(“Success create node :” + path2);*/  
  13.           
  14.         /*Asynchronous mode
  15.         zk.create(“/zk-test-ephemeral-“, “”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,new IStringCallback(),“i am context”);  
  16.         zk.create(“/zk-test-ephemeral-“, “”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL,new IStringCallback(),“i am context”);  
  17.         zk.create(“/zk-test-ephemeral-“, “”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL,new IStringCallback(),“i am context”);  
  18.         Thread.sleep(Integer.MAX_VALUE);  
  19.     }  
  20.       
  21.     @Override  
  22.     public void process(WatchedEvent event) {  
  23.         // TODO Auto-generated method stub  
  24.         if(KeeperState.SyncConnected == event.getState()){  
  25.             connectedSemaphore.countDown();  
  26.         }  
  27.     }  
  28. }  
  29.   
  30. class IStringCallback implements AsyncCallback.StringCallback{  
  31.   
  32.     @Override  
  33.     public void processResult(int rc, String path, Object ctx, String name) {  
  34.         // TODO Auto-generated method stub  
  35.         System.out.println(“Create path result: [” + rc + “,” + path + “,” + ctx + “, real path name ” + name);  
  36.     }  
  37.       
  38. }  

 

 

3.Delete node

 

[java] view plain copy

 
  1. zk.delete(path,version);  
  2. zk.delete(path,version,cb,ctx);  

Parameter Description:

 

path:Node path

version:version number

cb: callback

ctx: context

 

4.Obtaining child node

getChildrenThere are 8 overloaded methods

 

[java] view plain copy

 
  1.               zk.getChildren(path, watch);  
  2. zk.getChildren(path, watcher);  
  3. zk.getChildren(path, watch, stat);  
  4. zk.getChildren(path, watcher, stat);  
  5. zk.getChildren(path, watch, cb, ctx);  
  6. zk.getChildren(path, watcher, cb, ctx);  

There are two kinds of callback functions, namely, ChildrenCallback, Children2Callback

 

Parameter Description:

path:Node path

watch: booleanIf the type is true, the default Watcher is false, which means no Watcher is required.

watcher: The notification processor will receive the notification from the server once the child node changes.

stat: Specifies the node state information of the data node and passes it to an old stat object. After execution of the method, stat will be replaced by the new stat that the server responds.

cb:There are two types of callback functions that have already been said

ctx: context

 5.Getting node data

There are 4 overloading methods for getting node data

 

[java] view plain copy

 
  1.               zk.getData(path, watch, stat);  
  2. zk.getData(path, watcher, stat);  
  3. zk.getData(path, watch, cb, ctx);  
  4. zk.getData(path, watcher, cb, ctx);  

Parameter Description:

 

path: Node path

watch: booleanIf the type is true, the default Watcher is false, which means no Watcher is required.

stat: Specifies the node state information of the data node and passes it to an old stat object. After execution of the method, stat will be replaced by the new stat that the server responds.

cb:There are two types of callback functions that have already been said

ctx: context

When the registered watcher is getting the node data, the client is notified when the node data is sent, and when the client receives the notification, if the next data is sent, the notification is received again.

You need to re register watcher, and get the child node mechanism too.

6.Update node data

Updating node data is also divided into two methods: synchronous and asynchronous.

 

[java] view plain copy

 
  1. zk.setData(path, data, version);  
  2. zk.setData(path, data, version, cb, ctx);  

Parameter Description: the same

 

 

[java] view plain copy

 
  1. public class ZookeeperSampleGetDataTest implements Watcher {  
  2.   
  3.     public static CountDownLatch connectedSemaphore = new CountDownLatch(1);  
  4.       
  5.     public static Stat stat = new Stat();  
  6.       
  7.     public static ZooKeeper zk = null;  
  8.       
  9.     public static void main(String[] args) throws IOException, KeeperException, InterruptedException{  
  10.         String path = “/zk-test”;  
  11.         zk = new ZooKeeper(“192.168.1.138:2181”, 5000, new ZookeeperSampleGetDataTest());  
  12.         connectedSemaphore.await();  
  13.           
  14.         //Obtaining a child node
  15.         /*zk.delete(path, 0); 
  16.         zk.create(path, “”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 
  17.         zk.create(path+”/c1″, “”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 
  18.         //Synchronization method to obtain children
  19.         //List<String> childs = zk.getChildren(path, true); 
  20.         //System.out.println(childs); 
  21.         //Asynchronous method for obtaining children
  22.         zk.getChildren(path, true, new IChildren2Callback(), null); 
  23.          
  24.         zk.create(path+”/c2″, “”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); 
  25.         Thread.sleep(Integer.MAX_VALUE);*/  
  26.         //Obtaining node data
  27.         zk.delete(path, 0);  
  28.         zk.create(path, “123”.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);  
  29.           
  30.         System.out.println(new String(zk.getData(path, true, stat)));  
  31.         /** czxid: The transaction ID, mzxid: ID of the node is created to update the transaction ID version of the node.
  32.         System.out.println(“Czxid: ” + stat.getCzxid() + “Mzxid: ” + stat.getMzxid() + “Version: ” + stat.getVersion());  
  33.           
  34.         zk.setData(path, “123”.getBytes(), –1);  
  35.           
  36.         Thread.sleep(Integer.MAX_VALUE);  
  37.     }  
  38.       
  39.       
  40.     @Override  
  41.     public void process(WatchedEvent event) {  
  42.         // TODO Auto-generated method stub  
  43.         if(KeeperState.SyncConnected==event.getState()){  
  44.             if(EventType.None==event.getType() && null==event.getPath()){  
  45.                 connectedSemaphore.countDown();  
  46.             }else if(event.getType()==EventType.NodeChildrenChanged){  
  47.                 try {  
  48.                     System.out.println(“Get Child :” + zk.getChildren(event.getPath(), true));  
  49.                 } catch (KeeperException | InterruptedException e) {  
  50.                     // TODO Auto-generated catch block  
  51.                     e.printStackTrace();  
  52.                 }  
  53.             }else if(event.getType()==EventType.NodeDataChanged){  
  54.                 try {  
  55.                     System.out.println(new String(zk.getData(event.getPath(), true, stat)));  
  56.                     System.out.println(“Czxid: ” + stat.getCzxid() + “Mzxid: ” + stat.getMzxid() + “Version: ” + stat.getVersion());  
  57.                 } catch (KeeperException | InterruptedException e) {  
  58.                     // TODO Auto-generated catch block  
  59.                     e.printStackTrace();  
  60.                 }  
  61.             }      
  62.         }  
  63.     }  
  64. }  
  65.   
  66. class IChildren2Callback implements AsyncCallback.Children2Callback{  
  67.   
  68.     @Override  
  69.     public void processResult(int rc, String path, Object ctx,  
  70.             List<String> childrens, Stat stat) {  
  71.         // TODO Auto-generated method stub  
  72.         System.out.println(“Get Children znode result: [response code: ” + rc + “, param path: ” + path + “, ctx ” + ctx  
  73.                 + “, childrens :” +  childrens + “, stat: ” + stat);  
  74.     }  
  75.       
  76. }  

The update node data version version problem -1 indicates that the latest version of the data is updated here as an idea for a distributed lock. If the client’s version is not the latest version of the data, the update will fail.

 

For example, the current data version of the node “/zk-test” is 2 and a client tries to execute setData (“/zk-test”, “test”.GetBytes () (), 1) because the incoming version is 1 < the server listPrevious version 2 will update failure

7.Whether the detection node exists

 

[java] view plain copy

 
  1.               zk.exists(path, watch);  
  2. zk.exists(path, watcher);  
  3. zk.exists(path, watch, cb, ctx);  
  4. zk.exists(path, watcher, cb, ctx);  

If a node determines whether a node exists or not, the Watcher will monitor the presence of the node — creating a node, deleting the node, and notifying the client of the node data update

 

8.Authority control

zookeeperThe authority control mechanism of ACL is provided. Simply speaking, it controls client access to nodes by controlling the ACL of data nodes on the zookeeper server.

 

[java] view plain copy

 
  1. addAuthInfo(String scheme,byte[] auth);  

Parameter Description:

 

scheme: The access control mode is divided into: world, auth, digest, IP and super.

auth: The specific permission information is similar to the permission string of Shiro.

The following code:

 

[java] view plain copy

 
  1. <span style=“white-space:pre;”>     </span>ZooKeeper zk1 = new ZooKeeper(“192.168.1.138:2181”,5000,new ZookeeperSampleCreateTest());  
  2.         zk1.addAuthInfo(“digest”, “test:true”.getBytes());  
  3.         zk1.create(“/zk-test-auth”, “123”.getBytes(), Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);  
  4.         ZooKeeper zk2 = new ZooKeeper(“192.168.1.138:2181”,5000,new ZookeeperSampleCreateTest());  
  5.         zk2.addAuthInfo(“digest”, “test:true”.getBytes());  
  6.         System.out.println(new String(zk2.getData(“/zk-test-auth”, false, null)));  
  7.         ZooKeeper zk3 = new ZooKeeper(“192.168.1.138:2181”,5000,new ZookeeperSampleCreateTest());  
  8.         zk3.addAuthInfo(“digest”, “test:false”.getBytes());  
  9.         zk3.getData(“/zk-test-auth”, false, null);  

zk2The correct permissions are set so that the node data can be obtained, and ZK3 will throw exceptions.

 

 org.apache.zookeeper.KeeperException$NoAuthException: KeeperErrorCode = NoAuth for /zk-test-auth

Similar Posts:

Link of this Article: Zookeeper’s Java client API

Leave a Reply

Your email address will not be published. Required fields are marked *