Zookeeper command line and Java API for simple use

Source: Internet
Author: User
Tags zookeeper

installation
For zookeeper installation, please refer to this article: Zookeeper pseudo distributed cluster installation and usage

What I am using here is the installation and use of the zookeeper pseudo distribution pattern mentioned in the article.

command Line
The following instructions use zookeeper under the command line method.
Switch to the bin directory of the Zookeeper installation directory:

Command:zkserver.sh start zoo0.cfg
This command starts the Zkserver server. I am using pseudo distribution mode, three servers are native, only with a different port number, and configured in different configuration files, namely Zoo0.cfg, Zoo1.cfg, zoo2.cfg these three files are configured with the corresponding parameters and port number.

After you have started three servers, view the status of three servers:

Command:zkserver.sh status Zoo0.cfg
The state of three servers has two kinds, one follows state, the other is in a leading state.

After the server is started, you can connect through the client, as follows:

Command:zkcli.sh-server centos:2181
Where CentOS is my hostname, 2181 is the port number of the client connection server configured in the configuration file, which can be found in the Zoo0.cfg file. Accordingly, according to my pseudo distribution configuration, zkcli.sh-server centos:2182 This command can be connected to my second server, which can be found in zoo1.cfg files. When you use this command, you need to follow your own configuration to change the appropriate.
Through the log above, welcom to zookeeper. The output indicates that the client connected the server successfully.

Enter help command:

With this command, we can see what command lines the client can use ...
In fact, not much, just so few.

Command:
LS/
Stat/zookeeper

LS/command to see what nodes are under the root node. You can see that only one node is zookeeper.
The Stat/zookeeper command looks at the state information of the node zookeeper node.

Czxid represents the Zxid when the node is created,
Mzxid represents the current,
Zxid is used to serve the election leader.

CTime and Mtime, which represent the time of creation, which represents the time of the last update.
Note that the CTime is dead at the moment of creation, and Mtime will reset when you call the Change node function;
However, exists and get do not cause them to be updated.

Command:get/nodename

Command Get/nodename gets the data for the node path. Note: path must be an absolute path, which is the path that path must be/begin with.
The first node did not save the data, so there are no data in the three nodes.

To get quota information for child nodes:

To set data commands:
Set/nodepath Data Information

The data in the diagram to set the root node is the string "Longyin", and then the command gets: Get/
You can see that the value of datalength also changes.

Create node:create/path Data

Creates node nodes, and then outputs two nodes under the root node through LS.

To get the data and delete the node, command:
Get/node
Delete/node

Exit client, Command:
quit
Java API Interface operation

Import java.io.IOException;
Import Org.apache.zookeeper.CreateMode;
Import org.apache.zookeeper.KeeperException;
Import org.apache.zookeeper.WatchedEvent;
Import Org.apache.zookeeper.Watcher;
Import Org.apache.zookeeper.ZooDefs.Ids;

Import Org.apache.zookeeper.ZooKeeper; public class BasicDemo1 {public static void main (string[] args) throws IOException, Keeperexception 
         , Interruptedexception {/** * Creates a connection to the server * parameter one: server address and port number (the port number that the server allows the client to connect to, the default port number of the profile 2181) * Parameter two: Connection session timeout * Parameter Three: Observer, the connection success triggers the Observer.
         But it only triggers once.
            * The Watcher will obtain notification of various events/zookeeper ZK = new Zookeeper ("centos:2181", 60000, New Watcher () { Monitor all triggered events public void process (Watchedevent event) {System.out.println ("Monitor all triggered events: even
            T: "+ event.gettype ());
        }
        });
        System.out.println ("*******************************************************");
    To view the child nodes of the root node    System.out.println ("View child nodes of root node: LS/=>" + Zk.getchildren ("/", true));
        System.out.println ("*******************************************************"); Create a directory node if (zk.exists ("/node", true) = = null) {/** * parameter one: PATH address * parameter two: want to protect stored data, which needs to be converted to a byte array * parameter three: ACL access control List, * The parameter type provides some of the Arraylist<acl>,ids interface
             The default value can be invoked.
             * Open_acl_unsafe This is a completely open ACL * It's a completely open ACL, unsafe * Creator_all_acl This ACL gives the * Creators authentication ID ' s
             All permissions. * This ACL gives those authorized users permission * Read_acl_unsafe This ACL gives the world the Abilit
             Y to read.
             * This ACL gives the user permission to read, that is, to get the data. * Parameter four: the node type created. Enumeration value Createmode * Persistent (0, False, FALSE) * persistent_sequential (2, False, True) * These two types are created with persistent type nodes and will not be deleted automatically after the end of the conversation. * The difference is that the node name created by the second type will have a monotonically incremented value of * ephemeral (1, True, false) * EPH
             Emeral_sequential (3, True, True) * These two types create a temporary type node that is automatically deleted after the end of the reply.
             * The difference is that the temporary section name created by the second type is followed by a monotonically increasing number. * The return value of the last Create () method is the actual path of the created node/zk.create ("/node", "Conan". GetBytes (), IDS.O
            Pen_acl_unsafe, createmode.persistent);
            System.out.println ("Create a directory node: Create/node Conan"); /** * View/node node data, here should be output "Conan" * parameter one: Get the node's path * parameter two: to indicate whether the node needs to be observed, set to true, set the shared default Observer * Parameter three: Stat class, save node information. For example, data version information, creation time, modification time and other information * * SYSTEM.OUT.PRINTLN ("View/node node data: Get/node =>" +
            New String (Zk.getdata ("/node", false, null));
             /*** View root node * View the value of the root node here, the/node node created above should be exported/System.out.println ("View root node: ls/=>" +
        Zk.getchildren ("/", true));
        } System.out.println ("*******************************************************");
                    Create a subdirectory node if (zk.exists ("/node/sub1", true) = = null) {zk.create ("/node/sub1", "Sub1". GetBytes (),
            Ids.open_acl_unsafe, createmode.persistent);
            System.out.println ("Create a subdirectory node: create/node/sub1 sub1"); viewing node node System.out.println (View node nodes: Ls/node => + zk.getchildren ("/node", True)
        ;
        } System.out.println ("*******************************************************");
         /** * Modify node Data * Modified data overwrites the last set of data * SetData () method parameter one, parameter two is not much said, similar to the above. * Parameter three: numeric type.
         You need to pass in the numeric type version number of the interface ...
         * This information can be obtained through the stat class or through the command line.
         * If the value is set to-1, which is to ignore version matching, set the value of the node saved directly. */if (ZK.EXists ("/node", true)!= null) {Zk.setdata ("/node", "changed". GetBytes (),-1); View/node node Data System.out.println ("Modify node Data: Get/node =>" + New String (Zk.getdata ("/node
        ", false, null));
        } System.out.println ("*******************************************************");
            Delete node if (zk.exists ("/node/sub1", true)!= null) {Zk.delete ("/node/sub1",-1);
            Zk.delete ("/node",-1);
        View the root node System.out.println ("Delete node: ls/=>" + Zk.getchildren ("/", true));
    }//Close connection zk.close (); }
}

Most of the key code in the code already gives a detailed comment. The code completion function is also the same as the command line. Start Zookeeper first, then run the code:
The results are as follows:

As you can see, the results are the same as the actions we use on the command line. In the code we can use the observer to receive various events.

Finally, give a small sample code:

Import java.io.IOException;

Import java.util.ArrayList;
Import Org.apache.zookeeper.CreateMode;
Import org.apache.zookeeper.KeeperException;
Import org.apache.zookeeper.WatchedEvent;
Import Org.apache.zookeeper.Watcher;
Import Org.apache.zookeeper.ZooKeeper;

Import Org.apache.zookeeper.ZooDefs.Ids;  public class Queuezookeeper {public static void main (string[] args) throws Exception {if (args.length = 0)
        {Doone ();
        else {doaction (Integer.parseint (args[0]));
        The public static void Doone () throws Exception {String host1 = "centos:2181";
        Zookeeper ZK = connection (host1);
        Initqueue (ZK);
        Joinqueue (ZK, 1);
        Joinqueue (ZK, 2);
        Joinqueue (ZK, 3);
    Zk.close ();
        The public static void doaction (int client) throws Exception {String host1 = "centos:2181";
        String host2 = "centos:2182";

        String host3 = "centos:2183";
    Zookeeper ZK = null;    Switch (client) {Case 1:ZK = connection (host1);
            Initqueue (ZK);
            Joinqueue (ZK, 1);
        Break
            Case 2:ZK = connection (HOST2);
            Initqueue (ZK);
            Joinqueue (ZK, 2);
        Break
            Case 3:ZK = connection (HOST3);
            Initqueue (ZK);
            Joinqueue (ZK, 3);
        Break }//Create a connection to the server public static zookeeper connection (String host) throws IOException {zookeeper ZK  = New Zookeeper (host, 60000, new Watcher () {//monitor all triggered events public void process (Watchedevent event) {if (event.gettype () = = Event.EventType.NodeCreated && event.getpath
                (). Equals ("/queue/start")) {System.out.println ("queue has completed.finish testing!!!");
        }
            }
        });
    return to ZK; } public static void Initqueue (ZookeepEr zk) throws Keeperexception, interruptedexception {System.out.println ("WATCH =>/queue/start");
        Zk.exists ("/queue/start", true);
            /** * Create node/queue. Permanent node * Existence is not created, if it does not exist, create/if (Zk.exists ("/queue", false) = null) {
            System.out.println ("create=>/queue task-queue");
        Zk.create ("/queue", "Task-queue". GetBytes (), Ids.open_acl_unsafe, createmode.persistent);
        else {System.out.println ("/queue is exist!"); /** * Creates a child node of node/queue, (temporary node), after the session exits, the temporary node is deleted.
     and the temporary * node has a sequential number. * @param ZK * @param x * @throws keeperexception * @throws interruptedexception/public static V OID Joinqueue (zookeeper ZK, int x) throws Keeperexception, interruptedexception {System.out.println ("
        create=>/queue/x "+ x +" X "+ x); Zk.create ("/queue/x" + x, ("X" + x). GetBytes (), IdS.open_acl_unsafe, createmode.ephemeral_sequential);
    IsCompleted (ZK);  public static void IsCompleted (Zookeeper zk) throws Keeperexception, interruptedexception {int
        size = 3;
        arraylist<string> list = (arraylist<string>) zk.getchildren ("/queue", true);
        for (String str:list) {System.out.println ("Get child node of node queue: ls/queue:" +str);
        int length = List.size ();
        System.out.println ("Queue Complete:" + length + "/" + size+ "(Number of sub nodes/total length)");
            if (length >= size) {System.out.println ("Create temporary node: Create/queue/start start");
        Zk.create ("/queue/start", "Start". GetBytes (), Ids.open_acl_unsafe, createmode.ephemeral); } 
    }

}

The results of the operation are as follows:

From the results above, we can see that when we create a temporary node, the session ends and the temporary node is automatically deleted. We use the command line to view the root node information:

None of the nodes created in the code are.

Another note is that the node type we use is a temporary type of node type with sequential number, we found that during the session, we printed the name of the node after the 000000014,000000015,000000016, because I ran the code several times, so this value in a single increment, Increased to 16, from here we should know the meaning of the node of the sequence number type.

OK, end.

Code address for this project: please poke at this (Welcome to my GitHub)
Projects are built using Eclipse. Easy to use, code comment detail.

Related Article

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.