Zookeeper Client API Creation node (vii)

Source: Internet
Author: User
Tags response code zookeeper client

This blog focuses on using the Zookeeper native customer API to create a data node.

To create a data node method

Zookeeper provides two ways to create data nodes.

Synchronous creation of data node methods:

publiccreate(finalbyte data[], List<ACL> acl,            CreateMode createMode)        throws KeeperException, InterruptedException

To asynchronously create a data node method:

publicvoidcreate(finalbyte data[], List<ACL> acl,            CreateMode createMode,  StringCallback cb, Object ctx)
Parameter description
Parameter name Description
Path Create the path to the node, for example:/zk-test-create.
Data[] A byte array that creates the node initialization content. Users need to serialize and deserialize themselves. Complex objects can be serialized and deserialized using Hessian or Kryo.
Cc. ACL Policies for nodes
Createmode The type of the node is defined in enumeration Createmode: (1) Persistent: persistent, (2) Persistent_sequential: Persistent order, (3) Ephemeral: temporary, (4) Ephemeral_ Sequential: Temporary order.
Cb Asynchronously creates a method parameter. Register the callback function, need to implement Stringcallback interface. The main target is public void processresult (int rc, string path, Object ctx, string name), and interface overrides. This method is called for business logic processing after the data node creation is complete.
CTx Asynchronously creates a method parameter. The user passes an object that can be used when the callback method executes, usually by putting a context information
Create a node Demo

The following specific code to illustrate the use of different methods, for different methods have a corresponding comment description:

 PackageCom.secbro.learn;Importorg.apache.zookeeper.*;ImportJava.util.concurrent.CountDownLatch;/** * Created by Zhuzs on 2017/3/23. * * Public  class testcreatenode implements watcher {    Private StaticCountdownlatch Countdownlatch =NewCountdownlatch (1); Public Static void Main(string[] args)throwsException {ZooKeeper ZooKeeper =NewZooKeeper ("127.0.0.1:2181", the,NewTestcreatenode ()); Countdownlatch.await ();//Synchronize Create temporary nodeString Ephemeralpath = Zookeeper.create ("/zk-test-create-ephemeral-","123". GetBytes (), ZooDefs.Ids.OPEN_ACL_UNSAFE, createmode.ephemeral); System.out.println ("Synchronization creates temporary node success:"+ Ephemeralpath);//Synchronize Create temporary order nodeString Sequentialpath = Zookeeper.create ("/zk-test-create-sequential-","456". GetBytes (), ZooDefs.Ids.OPEN_ACL_UNSAFE, createmode.ephemeral_sequential); System.out.println ("Synchronization creates a temporary order node successfully:"+ Sequentialpath);//Create temporary nodes asynchronouslyZookeeper.create ("/zk-test-create-async-ephemeral-","ABC". GetBytes (), ZooDefs.Ids.OPEN_ACL_UNSAFE, Createmode.ephemeral,NewMystringcallback (),"I am delivering content");//asynchronously creates a temporary order nodeZookeeper.create ("/zk-test-create-async-sequential-","Def". GetBytes (), ZooDefs.Ids.OPEN_ACL_UNSAFE, Createmode.ephemeral_sequential,NewMystringcallback (),"I am delivering content"); Thread.Sleep (10000);//Verify wait for callback results to be used, can adjust according to the actual situation} Public void Process(Watchedevent event) {if(Event.KeeperState.SyncConnected = = Event.getstate ())        {Countdownlatch.countdown (); }}}class Mystringcallback implements Asynccallback.stringcallback { Public void Processresult(intRC, String path, Object ctx, string name) {System.out.println ("Asynchronous Create callback Result: Status:"+ RC +"; Create path:"+ Path +"; Pass the message:"+ CTX +"; actual node name:"+ name); }}

The output is:

Synchronization to create a temporary node success:/ZK-test-create-ephemeral-Synchronize create staging Sequence node success:/ZK-test-create-sequential-0000000023Asynchronous create callback Result: status:0; Create path:/ZK-test-create-async-ephemeral-; Passing information: I am passing content; actual node name:/ZK-test-create-async-ephemeral-Asynchronous create callback Result: status:0; Create path:/ZK-test-create-async-sequential-; Passing information: I am passing content; actual node name:/ZK-test-create-async-sequential-0000000025

Based on the above code and results, it is easy to know how different methods are used.

Precautions

(1) Zookeeper does not support recursive creation of data nodes and cannot create child nodes without the parent node being present. Otherwise, it throws an exception similar to the following:

ExceptioninchThread"Main"Org. Apache. Zookeeper. Keeperexception$NoNodeException: Keepererrorcode = Nonode for/zk-test-create-sequential-/ Oneat org. Apache. Zookeeper. Keeperexception. Create(keeperexception. Java:111) at Org. Apache. Zookeeper. Keeperexception. Create(keeperexception. Java:Wuyi) at Org. Apache. Zookeeper. ZooKeeper. Create(ZooKeeper. Java:783) atcom. Secbro. Learn. Testcreatenode. Main(Testcreatenode. Java: -) at Sun. Reflect. Nativemethodaccessorimpl. Invoke0 (Native Method) at Sun. Reflect. Nativemethodaccessorimpl. Invoke(Nativemethodaccessorimpl. Java: $) at Sun. Reflect. Delegatingmethodaccessorimpl. Invoke(Delegatingmethodaccessorimpl. Java: +) at Java. Lang. Reflect. Method. Invoke(Method. Java:606) atcom. IntelliJ. RT. Execution. Application. Appmain. Main(Appmain. Java:147)

(2) If the node already exists, and then create the same honour point, the nodeexistsexception will be thrown.
(3) Regarding the permission control, if there is no special request, can be set directly to ZooDefs.Ids.OPEN_ACL_UNSAFE in the above example, indicate that any operation to the node is not controlled by permission.

Stringcallback Interface Related

The Stringcallback interface integrates the AsyncCallback interface to implement business processing at callbacks. The AsyncCallback interface also includes 8 callback interfaces: Statcallback, Datacallback, Aclcallback, Childrencallback, Children2callback, Voidcallback, Multicallback, Stringcallback. Different callback interfaces can be implemented in different asynchronous interfaces.

The public void Processresult (int rc, string path, Object ctx, String name) method of the Stringcallback interface.
As you can see from the example above.
The int RC is the server's response code, 0 indicates a successful call, 4 indicates that the connection is broken, and 110 indicates that the specified node already exists, and 112 indicates that the session has expired.
String path to the path that was passed when the Create method was called.
Object CTX invokes the CTX when the Create method is passed.
String name creates the successful node names.

Zookeeper Client API Creation node (vii)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.