- Create Session
1 package org.zln.zk; 2 3 import org.apache.zookeeper.WatchedEvent; 4 import org.apache.zookeeper.Watcher; 5 import org.apache.zookeeper.ZooKeeper; 6 7 import java.io.IOException; 8 9 /** 10 * Created by sherry on 16/8/27. 11 */ 12 public class TestZooKeeperClientApi { 13 14 private static ZooKeeper zooKeeper; 15 16 public static void main(String[] args) throws IOException, InterruptedException { 17 createSession(); 18 } 19 20 /** 21 * 创建会话 22 */ Private static ZooKeeper the createSession 23 is () throws IOException, InterruptedException { 24 // instantiation process, but also the process connected to establishing ZooKeeper, Parameter: ip: port listener timeout (implemented water interface for receiving a notification listener) the ZooKeeper ZooKeeper new new = 25 ( "127.0.0.1:2181", 5000, new new Watcher () { 26 is @Override 27 public void Process (watchedEvent watchedEvent) { 28 System.out.println ( "receive event:" + watchedEvent); // receive event: WatchedEvent state: SyncConnected type: None path: null 29 30 31 is the TODO // 32} 33 is}); 34 is System.out.println ( "Check status:" + zooKeeper.getState ()); // Check status: CONNECTING The 35 36 // if kept for some time, then the listener listens not received, the method has been pulled out 37 [the Thread.sleep (5000); 38 is 39 return zooKeeper; 40 41 42 } 43 }
- Creating nodes
1 package org.zln.zk; 2 3 import org.apache.zookeeper.*; 4 import org.apache.zookeeper.data.ACL; 5 import org.slf4j.Logger; 6 import org.slf4j.LoggerFactory; 7 8 import java.io.IOException; 9 import java.io.UnsupportedEncodingException; 10 import java.util.ArrayList; 11 12 /** 13 * Created by sherry on 16/8/27. 14 */ 15 public class TestZooKeeperClientApi { 16 17 private static Logger logger = LoggerFactory.getLogger(TestZooKeeperClientApi.class); 18 19 private static ZooKeeper zooKeeper; 20 Public static void main 21 is (String [] args) throws IOException, InterruptedException { 22 is the createSession (); 23 is} 24 25 / ** 26 is to create a session * 27 * / 28 Private the ZooKeeper the createSession static () throws IOException, InterruptedException { 29 // examples of the process, but also the establishment of the connection with ZooKeeper, parameter: ip: port listener timeout (implemented water interface for receiving a notification listener) 30 ZooKeeper ZooKeeper new new = ( "127.0.0.1:2181", 5000 , new new Watcher () { 31 is @Override 32 public void Process (watchedEvent watchedEvent) { interact with ZooKeeper 33 // TODO, are generally placed here 34 if (watchedEvent.getState () == Event.KeeperState.SyncConnected ) {/ /connected 35 logger.info ( "the connected"); 36 37 [{the try 38 is // Parameters: byte array authority node data path model created by node 39 String nodePath = createNode (zooKeeper, "/ node_1", "123". the getBytes ( "UTF-. 8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 40 logger.info ( "Create node:" + NodePath); 41 is the catch} (UnsupportedEncodingException | KeeperException | InterruptedException E) { 42 is e.printStackTrace (); 43 is} 44 is 45} 46 is} 47}); 48 logger.info ( "Check status:" + zooKeeper.getState ()); // Check status:CONNECTING 49 50 // stop if a period of time, then the listener listens not received, a method has been pulled out of 51 is the Thread.sleep (5000); 52 is 53 is return ZooKeeper; 54 is 55 56 is} 57 is 58 / ** 59 * Create ZooKeeper node 60 * @param zooKeeper ZooKeeper connection 61 * @return node path 62 is * / 63 is the createNode String public static (the ZooKeeper ZooKeeper, String path, byte [] bytes, the ArrayList <the ACL> ACLs and, CreateMode createMode) throws UnsupportedEncodingException, KeeperException, InterruptedException { 64 // parameters: byte array authority node data path model created by node 65 return zooKeeper.create (path, bytes, ACLs and, createMode); 66} 67}
Creation mode
PERSISTENT lasting node
PERSISTENT_SEQUENTIAL lasting order of nodes
EPHEMERAL temporary node
EPHEMERAL_SEQUENTIAL interim order of the nodes
This code is part of sync creation
1 / * 2 * Create asynchronous nodes . 3 * @param ZooKeeper . 4 * @param path . 5 * @param bytes . 6 * @param ACLs and . 7 * @param createMode . 8 * @throws KeeperException . 9 @throws InterruptedException * 10 * / . 11 public static asCreateNode void (the ZooKeeper ZooKeeper, String path, byte [] bytes, the ArrayList <the ACL> ACLs and, createMode createMode) throws KeeperException, {InterruptedException 12 is 13 is the need to increase AsyncCallback.StringCallback // Create asynchronous interface implementation class and a context object parameters 14 zooKeeper .create (path, bytes, ACLs and, createMode, new new AsyncCallback.StringCallback () { 15 / ** 16 * 17 * @param rc node create node 0- results return code to create a successful 18 * @param path node real path last parameter that 19 * @param ctx asynchronous method call context is create a local call 20 * @param name 21 * / 22 @override 23 is public void processResult (int RC, path String, Object CTX, String name) { 24 = the StringBuilder StringBuilder the StringBuilder new new (); 25 StringBuilder.Append ( "\ NRC =" + RC + "\ n-" + 26 is "path = "path + +" \ n-"+ 27" CTX = "+ CTX +" \ n-"+ 28" name = "+ name +" \ n-"); 29 logger.info (StringBuilder.ToString ()); 30 } 31}, "Asynchronous Create"); 32}
- Getting child nodes
1 / * 2 * synchronization acquisition sub-mode node 3 * @param zooKeeper connector 4 * @param parentPath parent paths . 5 * @return . 6 * @throws KeeperException . 7 * @throws InterruptedException . 8 * / . 9 public static List <String> getChildList ( ZooKeeper the ZooKeeper, String parentPath) throws KeeperException, InterruptedException { 10 // parameters: parent node path require attention to changes in the child node . 11 List <String> = zooKeeper.getChildren Childs (parentPath, to false); 12 is return Childs; 13 is}
1 / * 2 * asynchronously acquired child node subnode concerned change 3 * @param zooKeeper connector 4 * @param parentPath parent paths . 5 * / . 6 asGetChildListAndWatch public static void (the ZooKeeper ZooKeeper, String parentPath) { . 7 zooKeeper.getChildren (parentPath , to true, new new AsyncCallback.Children2Callback () { . 8 @Override . 9 processResult public void (int RC, String path, CTX Object, List <String> Children, Stat STAT) { 10 logger.info ( "child node after the change:" ); . 11 for (String name: Children) { 12 is logger.info ( "child nodes:" + name); 13 is} 14} 15}, "child node of interest change"); 16 }
So far this rule can be found, the callback function is invoked asynchronously, the callback function is not synchronous call
Q: Scene synchronous and asynchronous calls are calls? ? ?
A: The following operations depend on the result of calling time, you need to call synchronization method
1 package org.zln.zk; 2 3 import org.apache.zookeeper.*; 4 import org.apache.zookeeper.data.ACL; 5 import org.apache.zookeeper.data.Stat; 6 import org.slf4j.Logger; 7 import org.slf4j.LoggerFactory; 8 9 import java.io.IOException; 10 import java.io.UnsupportedEncodingException; 11 import java.util.ArrayList; 12 import java.util.List; 13 14 /** 15 * Created by sherry on 16/8/27. 16 */ 17 public class TestZooKeeperClientApi { 18 19 private static Logger logger = LoggerFactory.getLogger(TestZooKeeperClientApi.class); 20 Private static ZooKeeper the ZooKeeper 21 is; 22 is 23 is public static void main (String [] args) throws IOException, InterruptedException { 24 the createSession (); 25 26 is the Thread.sleep (Integer.MAX_VALUE); 27} 28 29 / ** 30 * Create Session * 31 is / 32 the ZooKeeper the createSession Private static () throws IOException, InterruptedException { 33 is // instantiation process, but also the process of establishing a connection with the ZooKeeper, parameters: ip: port listener timeout (implemented water interfaces, for listeners receiving notifications) 34 is the ZooKeeper ZooKeeper new new = ( "127.0.0.1:2181", 5000, new new Watcher () { 35 @Override 36 public void Process (watchedEvent watchedEvent) { 37 // TODO interaction with ZooKeeper, are generally placed here 38 if (watchedEvent.getState () == Event.KeeperState.SyncConnected ) {// connected 39 logger.info ( "the connected"); 40 the try { 41 // Create a synchronous node 42 is NodePath // String = sysCreateNode (ZooKeeper, "/ Node_1", "123" .getBytes ( "UTF-. 8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); 43 is // Logger .info ( "Create node:" + NodePath); 44 is 45 // created asynchronously node 46 //asCreateNode(zooKeeper,"/node_2","234".getBytes("UTF-8 "), ZooDefs.Ids.OPEN_ACL_UNSAFE , CreateMode.PERSISTENT); 47 48 49 // child node synchronization acquisition mode change child node of interest 50 // List <String> List = getChildListNoWatch (ZooKeeper, "/"); 51 is for // (String name: List) { 52 is logger.info // ( " child nodes: "+ name); 53 is //} 54 is 55 // asynchronously acquired child node of interest change 56 is asGetChildListAndWatch // (ZooKeeper," / "); 57 is 58 // node data acquired in a synchronized manner sysGetNodeData 59 60 byte [ ] bytes = sysGetNodeDataNoWatch (ZooKeeper, "/ Node_1"); 61 is logger.info ( "Get node data" + new String (bytes, " UTF-8")); 62 63 deleteNode(zooKeeper,"/node_1",0); } The catch 64 (KeeperException | InterruptedException | UnsupportedEncodingException E) { 65 e.printStackTrace (); 66} 67 68} 69} 70}); 71 is logger.info ( "Check Status:" + zooKeeper.getState ()); // Check status: cONNECTING The 72 73 is return ZooKeeper; 74 75 76} 77 78 / ** 79 * Create sync node 80 * @param zooKeeper connector 81 * @param path node path 82 * @param bytes byte array data 83 * @param acls permissions 84 * @param createMode creation mode @Return * 85 86 * @throws UnsupportedEncodingException 87 * @throws KeeperException 88 @throws InterruptedException * 89 * / 90 public static String sysCreateNode (the ZooKeeper ZooKeeper, String path, byte [] bytes, the ArrayList <the ACL> ACLs and, CreateMode createMode) throws UnsupportedEncodingException , KeeperException, {InterruptedException 91 is return zooKeeper.create (path, bytes, ACLs and, createMode); 92} 93 94 95 / ** 96 * Create asynchronous node 97 * @param zooKeeper connector 98 * @param path node path 99 * @param byte array of data bytes 100 * @param acls permissions 101 * @param createMode creation mode 102 * @throws KeeperException 103 @throws InterruptedException * 104 * / 105 public static void asCreateNode (the ZooKeeper ZooKeeper, String path, byte [] bytes, the ArrayList <the ACL> ACLs and, CreateMode createMode) throws KeeperException, InterruptedException { 106 107 // create a need to increase AsyncCallback.StringCallback asynchronous interface implementation class parameter and a context object 108 zooKeeper.create (path, bytes, ACLs and, createMode, new new AsyncCallback.StringCallback () { 109 / ** 110 * 111 * @ param rc node create node 0- results return code is successfully created 112 * @param path node real path last argument that 113 * @param ctx asynchronous method call context is create a local call 114 * @param name 115 */ 116 @Override 117 public void processResult(int rc, String path, Object ctx, String name) { 118 StringBuilder stringBuilder = new StringBuilder(); 119 stringBuilder.append("\nrc="+rc+"\n" + 120 "path="+path+"\n" + 121 "ctx="+ctx+"\n" + 122 "name="+name+"\n"); 123 logger.info(stringBuilder.toString()); 124 } 125 },"异步创建"); 130 * Get the child node in a synchronized manner does not change the child node of interest 129 / ** 128 127 126} 131 * @param zooKeeper connector 132 * @param parentPath parent paths 133 @return * 134 * @throws KeeperException 135 @throws InterruptedException * 136 * / 137 public static List <String> sysGetChildListNoWatch (the ZooKeeper ZooKeeper, String parentPath) throws KeeperException, InterruptedException { 138 // parameters: concern whether the parent node after path change child node if true, then the child node changes, an event is generated NodeChildrenChanged 139 List <String> = zooKeeper.getChildren Childs (parentPath, to false); 140 return Childs; 141} 142 143 / ** 144 * asynchronously acquired child node subnode concerned changes 145 * @param zooKeeper connector 146 * @param parentPath parent paths * 147/ 148 static public void asGetChildListAndWatch (the ZooKeeper ZooKeeper, String parentPath) { 149 zooKeeper.getChildren (parentPath, to true, new new AsyncCallback.Children2Callback () { 150 @Override 151 public void processResult (int RC, String path, CTX Object, List <String> Children, Stat STAT) { "child node after the change:" 152 logger.info (); 153 for (String name: Children) { 154 logger.info ( "child nodes:" + name); 155} 156 } 157}, "concerned about the child node change"); 158} 159 160 / ** 161 * synchronous mode data acquisition 162 * @param ZooKeeper 163 * @param path * @Return 164 is 165 * @throws KeeperException 166 * @throws InterruptedException 167 is * / 168 public static byte [] sysGetNodeDataNoWatch (the ZooKeeper ZooKeeper, String path) throws KeeperException, InterruptedException { 169 // change state of focus data path is 170 return zooKeeper.getData (path, to false, new new Stat ()); 171 is} 172 173 / ** 174 * delete nodes 175 * @param ZooKeeper 176 * @param NodePath 177 * @param Version 178 @throws KeeperException * 179 * @throws InterruptedException 180 [* / 181 public static void deleteNode(ZooKeeper zooKeeper,String nodePath,int version) throws KeeperException, InterruptedException { 182 zooKeeper.delete(nodePath,version); 183 } 184 185 186 }
In addition to the Java API ZooKeeper provided, there are two client, ZKClient and Curator both clients are native API of the package, making the operation more convenient
"Consistency Principles and Practice from PAXOS distributed to ZOOKEEPER" can refer to the book