[Series] 2. ZooKeeper ZooKeeper API calls in Java

温馨提示: Here I again mention a little requirements, I hope you can get used to look at the official document , although the document is in English, but words are relatively simple, can understand the basic document expressing the meaning. Teach him to fish than teach him to fish reason I believe we all understand, and hope that through this valley ape ZooKeeper series, so that we get started, to the familiar, after giving top priority to proficiency ZooKeeper.

In a previous we introduced ZooKeeper stand-alone version, pseudo-cluster environment to build , through the command line did create nodes, delete, update, access node test information. Zookeeper purpose is to provide a simple, efficient core API to build complex client coordination function, this one we use Java API interface provided by ZooKeeper to achieve these CRUD functionality.

1 Introduction

org.apache.zookeeper.ZookeeperIs the main class ZooKeeper client, in official documents has been clearly stated (This is the main class of ZooKeeper client library.).

This is the main class of ZooKeeper client library. To use a ZooKeeper service, an application must first instantiate an object of ZooKeeper class. All the iterations will be done by calling the methods of ZooKeeper class. The methods of this class are thread-safe unless otherwise noted.
Once a connection to a server is established, a session ID is assigned to the client. The client will send heart beats to the server periodically to keep the session valid.

Create an instance of a ZooKeeper to use org.apache.zookeeper.Zookeeperin the method, the official noted that the document has not specifically stated, then, ZooKeeper class of methods is 线程安全of. ZooKeeper client to connect to the service, the client will assign a session ID (session ID), the client and server to keep the session will be effective heartbeat.

org.apache.zookeeper.ZookeeperIn the method very much, I will not list them, only a few columns of CRUD.
| Method, | the Description |
| - | - |
| the Create (String path, byte [] the Data, List acl, CreateMode createMode) | Create a node with the given path ( to create the specified path nodes) |.
| the Create (String path, byte [] the Data, List acl, CreateMode createMode, AsyncCallback.Create2Callback cb, Object ctx) | The asynchronous version of create.(异步形式创建) |
| create(String path, byte[] data, List acl, CreateMode createMode, Stat stat) | Create a node with the given path and returns the Stat of that node ( create a node at the specified path and return node status information) |.
| the Delete (String path, int Version) | the Delete at The the Node with the given path (delete nodes specified path) |.
| the delete (String path, int Version, AsyncCallback.VoidCallback cb, Object ctx) | at the asynchronous Version of the delete (asynchronous delete nodes specified path) |.
| EXISTS (String path, boolean watch) | return the stat of the node of the given path ( of the specified path node state information) |.
| the getChildren (String path, Boolean Watch) | the return the List of the Children of the node of the GIVEN path . (of the specified path all the child nodes state information) |
| the getData (String path, Boolean Watch, Stat STAT) |. the return the data and the STAT of the node of the GIVEN path (of the specified path node data and status information ) |
| SetData (String path, byte [] data, int version) | Set the data for the node of the given path if such a node exists and the given version matches the version of the node (if the given version is -1, it . matches any node's versions) (designated path to the node and set the new value of the version, such as version -1, i.e., set values ​​for all versions) |

2, test environment

Here a new Boot Spring project to test the new Spring Boot project is a simple process, nor is the focus here, not be introduced.

Project was introduced two packages will require additional testing:

        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.5.5</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.5.2</version>
        </dependency>

3 API test

Complete test code as follows:

/**
 *  简单测试示例
 * @author 猿人谷
 * @date 2019/12/16
 */
public class ZooKeeperDemo {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZooKeeperDemo.class);

    private static final int SESSION_TIME_OUT = 10000;
    // ZooKeeper服务的地址,如为集群,多个地址用逗号分隔
    private static final String CONNECT_STRING = "127.0.0.1:2181";
    private static final String ZNODE_PATH = "/zk_demo";
    private static final String ZNODE_PATH_PARENT = "/app1";
    private static final String ZNODE_PATH_CHILDREN = "/app1/app1_1";

    private ZooKeeper zk = null;

    @Before
    public void init() throws IOException {
        zk = new ZooKeeper(CONNECT_STRING, SESSION_TIME_OUT, new Watcher(){
            @Override
            public void process(WatchedEvent event) {
                System.out.println("已经触发了" + event.getType() + "事件!");
            }
        });

    }

    @Test
    public void testCreate() throws KeeperException, InterruptedException {
        zk.create(ZNODE_PATH, "anna2019".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void testCreateParentZnode() throws KeeperException, InterruptedException {
        zk.create(ZNODE_PATH_PARENT, "anna2019".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void testCreateChildrenZnode() throws KeeperException, InterruptedException {
        zk.create(ZNODE_PATH_CHILDREN, "anna2020".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void testGet() throws KeeperException, InterruptedException {
        byte[] data1 = zk.getData(ZNODE_PATH, false, null);
        byte[] data2 = zk.getData(ZNODE_PATH_PARENT, false, null);
        byte[] data3 = zk.getData(ZNODE_PATH_CHILDREN, false, null);
        LOGGER.info("{}的信息:{}", ZNODE_PATH, new String(data1) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_PARENT, new String(data2) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_CHILDREN, new String(data3) );
    }

    /**
     *  删除
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testDelete() throws KeeperException, InterruptedException {
        // 指定要删除的版本,-1表示删除所有版本
        zk.delete(ZNODE_PATH, -1);
    }

    /**
     *  删除含有子节点
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testDeleteHasChildrenZnode() throws KeeperException, InterruptedException {
        // 指定要删除的版本,-1表示删除所有版本
        zk.delete(ZNODE_PATH_PARENT, -1);
    }

    @Test
    public void testSet() throws KeeperException, InterruptedException {
        Stat stat = zk.setData(ZNODE_PATH, "yuanrengu".getBytes(), -1);
        LOGGER.info(stat.toString());
    }

}

Useful to the above @Beforedescribed briefly below:

  • @BeforeClass - represents performed before any public static void method performed in a class
  • @AfterClass - represents performed after any public static void method performed in a class
  • @Before - represents executed before any public void method using @Test notes marked execution
  • @After - represents executed after public void any method of execution using @Test comment marked
  • @Test - public void method using the annotation label will be represented as a test method

If SESSION_TIME_OUT time is set too short, it will be reported in client API exception: org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /zk_demo. Complete the following error message:

09:33:52.139 [main-SendThread(106.12.111.172:2181)] DEBUG org.apache.zookeeper.ClientCnxnSocketNIO - Ignoring exception during shutdown input
java.net.SocketException: Socket is not connected
    at sun.nio.ch.Net.translateToSocketException(Net.java:123)
    at sun.nio.ch.Net.translateException(Net.java:157)
    at sun.nio.ch.Net.translateException(Net.java:163)
    at sun.nio.ch.SocketAdaptor.shutdownInput(SocketAdaptor.java:401)
    at org.apache.zookeeper.ClientCnxnSocketNIO.cleanup(ClientCnxnSocketNIO.java:198)
    at org.apache.zookeeper.ClientCnxn$SendThread.cleanup(ClientCnxn.java:1338)
    at org.apache.zookeeper.ClientCnxn$SendThread.cleanAndNotifyState(ClientCnxn.java:1276)
    at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1254)
Caused by: java.nio.channels.NotYetConnectedException: null
    at sun.nio.ch.SocketChannelImpl.shutdownInput(SocketChannelImpl.java:782)
    at sun.nio.ch.SocketAdaptor.shutdownInput(SocketAdaptor.java:399)
    ... 4 common frames omitted
09:33:52.140 [main-SendThread(106.12.111.172:2181)] DEBUG org.apache.zookeeper.ClientCnxnSocketNIO - Ignoring exception during shutdown output
java.net.SocketException: Socket is not connected
    at sun.nio.ch.Net.translateToSocketException(Net.java:123)
    at sun.nio.ch.Net.translateException(Net.java:157)
    at sun.nio.ch.Net.translateException(Net.java:163)
    at sun.nio.ch.SocketAdaptor.shutdownOutput(SocketAdaptor.java:409)
    at org.apache.zookeeper.ClientCnxnSocketNIO.cleanup(ClientCnxnSocketNIO.java:205)
    at org.apache.zookeeper.ClientCnxn$SendThread.cleanup(ClientCnxn.java:1338)
    at org.apache.zookeeper.ClientCnxn$SendThread.cleanAndNotifyState(ClientCnxn.java:1276)
    at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1254)
Caused by: java.nio.channels.NotYetConnectedException: null
    at sun.nio.ch.SocketChannelImpl.shutdownOutput(SocketChannelImpl.java:799)
    at sun.nio.ch.SocketAdaptor.shutdownOutput(SocketAdaptor.java:407)
    ... 4 common frames omitted

org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /zk_demo

    at org.apache.zookeeper.KeeperException.create(KeeperException.java:102)
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:54)
    at org.apache.zookeeper.ZooKeeper.getData(ZooKeeper.java:2131)
    at org.apache.zookeeper.ZooKeeper.getData(ZooKeeper.java:2160)
    at com.yuanrengu.demo.ZooKeeperDemo.testGet(ZooKeeperDemo.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Disconnected from the target VM, address: '127.0.0.1:60454', transport: 'socket'

Process finished with exit code -1

At first thought it was a problem with deploying ZooKeeper service or service did not start after confirmation by check, debug debugging found that SESSION_TIME_OUT = 2000; value is too small, the 10000 changed to no longer being given.

SESSION_TIME_OUT Shi 会话超时时间, that is, when a zookeeper exceeds the time no heartbeat, the node is considered a failure. So, if this value is less than zookeeper creation time, when the zookeeper had time to create a connection, session time has come, therefore considered that an exception is thrown node failure.

3.1 New

public String create(String path,
                     byte[] data,
                     List<ACL> acl,
                     CreateMode createMode)
              throws KeeperException,
                     InterruptedException
                     
Create a node with the given path. The node data will be the given data, and node acl will be the given acl.
The flags argument specifies whether the created node will be ephemeral or not.

An ephemeral node will be removed by the ZooKeeper automatically when the session associated with the creation of the node expires.

The flags argument can also specify to create a sequential node. The actual path name of a sequential node will be the given path plus a suffix "i" where i is the current sequential number of the node. The sequence number is always fixed length of 10 digits, 0 padded. Once such a node is created, the sequential number will be incremented by one.

If a node with the same actual path already exists in the ZooKeeper, a KeeperException with error code KeeperException.NodeExists will be thrown. Note that since a different actual path is used for each invocation of creating sequential node with the same path argument, the call will never throw "file exists" KeeperException.

If the parent node does not exist in the ZooKeeper, a KeeperException with error code KeeperException.NoNode will be thrown.

An ephemeral node cannot have children. If the parent node of the given path is ephemeral, a KeeperException with error code KeeperException.NoChildrenForEphemerals will be thrown.

This operation, if successful, will trigger all the watches left on the node of the given path by exists and getData API calls, and the watches left on the parent node by getChildren API calls.

If a node is created successfully, the ZooKeeper server will trigger the watches on the path left by exists calls, and the watches on the parent of the node by getChildren calls.

The maximum allowable size of the data array is 1 MB (1,048,576 bytes). Arrays larger than this will cause a KeeperExecption to be thrown.

Parameters:
path - the path for the node
data - the initial data for the node
acl - the acl for the node
createMode - specifying whether the node to be created is ephemeral and/or sequential
Returns:
the actual path of the created node
Throws:
KeeperException - if the server returns a non-zero error code
KeeperException.InvalidACLException - if the ACL is invalid, null, or empty
InterruptedException - if the transaction is interrupted
IllegalArgumentException - if an invalid path is specified

Talk is cheap. Show me the code. Here we are not blind BB, directly on official documents. Official documentation is not very easy to understand, and explain very clearly (and somewhat long-winded feeling)?

Here a simple column at several key points in the document :

  1. The specified path and node creation form, can be specified as persistent node node, such as temporary node.
    Under say here CreateMode, we may say that only four forms of ZooKeeper nodes (persistent, temporary, lasting order, temporary order), see the document, in fact, there is a 7种form.
public enum CreateMode {
   PERSISTENT(0, false, false, false, false),
   PERSISTENT_SEQUENTIAL(2, false, true, false, false),
   EPHEMERAL(1, true, false, false, false),
   EPHEMERAL_SEQUENTIAL(3, true, true, false, false),
   CONTAINER(4, false, false, true, false),
   PERSISTENT_WITH_TTL(5, false, false, false, true),
   PERSISTENT_SEQUENTIAL_WITH_TTL(6, false, true, false, true);
}
  • PERSISTENT: Persistent nodes (also called permanent node), will not be automatically deleted with the end of the session.
  • PERSISTENT_SEQUENTIAL: with a monotonically increasing number of nodes lasting, will not be automatically deleted with the end of the session.
  • EPHEMERAL: temporary node will be automatically deleted with the end of the session.
  • EPHEMERAL_SEQUENTIAL: temporary node with monotonically increasing numbers, will be automatically deleted with the end of the session.
  • CONTAINER: Container node for Leader, Lock and other special purposes, when the container node any child node does not exist, the container will be the candidate node server removed sometime in the future.
  • PERSISTENT_WITH_TTL: Persistent node with TTL (time-to-live, survival time), the node has not been updated within the TTL of time and have no children, it will be automatically deleted.
  • PERSISTENT_SEQUENTIAL_WITH_TTL: With TTL (time-to-live, survival time) and lasting monotonically increasing number of nodes, the nodes are not updated within the TTL of time and have no children, it will be automatically deleted.
  1. If the instruction path and version of nodes already exist, it will throw a KeeperException exception.
  2. 临时节点不能有子节点. If you create a child node to node throw KeeperException temporary exception.
  3. Lifecycle temporary node is associated with a client session. Once the client session expires (the client and Zookeeper not necessarily disconnected session expires), then the client creates all temporary nodes will be removed .
  4. byte[] data允许的最大数据量为1MB(1,048,576 bytes). If so, you will throw KeeperExecption.

Run the code that creates the node:

    @Test
    public void testCreate() throws KeeperException, InterruptedException {
        zk.create(ZNODE_PATH, "anna2019".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

You can create a successful log information obtained through the node:

DEBUG org.apache.zookeeper.ClientCnxn - Reading reply sessionid:0x101402626bb000b, packet:: clientPath:null serverPath:null finished:false header:: 1,1  replyHeader:: 1,12884901937,0  request:: '/zk_demo,#616e6e6132303139,v{s{31,s{'world,'anyone}}},0  response:: '/zk_demo

In the service side to view, create success / zk_demo node:

[zk: 127.0.0.1:2181(CONNECTED) 21] ls /
[zookeeper, zk_demo]
[zk: 127.0.0.1:2181(CONNECTED) 22] stat /zk_demo
cZxid = 0x300000031
ctime = Tue Dec 17 12:52:50 CST 2019
mZxid = 0x300000031
mtime = Tue Dec 17 12:52:50 CST 2019
pZxid = 0x300000031
cversion = 0
dataVersion = 0
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 8
numChildren = 0

3.2 Gets

public byte[] getData(String path,
                      boolean watch,
                      Stat stat)
               throws KeeperException,
                      InterruptedException

Return the data and the stat of the node of the given path.
If the watch is true and the call is successful (no exception is thrown), a watch will be left on the node with the given path. The watch will be triggered by a successful operation that sets data on the node, or deletes the node.

A KeeperException with error code KeeperException.NoNode will be thrown if no node with the given path exists.

Parameters:
path - the given path
watch - whether need to watch this node
stat - the stat of the node
Returns:
the data of the node
Throws:
KeeperException - If the server signals an error with a non-zero error code
InterruptedException - If the server transaction is interrupted.

KeeperException.NoNode node to throw an exception when the specified path does not exist.

run:

    @Test
    public void testGet() throws KeeperException, InterruptedException {
        byte[] data1 = zk.getData(ZNODE_PATH, false, null);
        byte[] data2 = zk.getData(ZNODE_PATH_PARENT, false, null);
        byte[] data3 = zk.getData(ZNODE_PATH_CHILDREN, false, null);
        LOGGER.info("{}的信息:{}", ZNODE_PATH, new String(data1) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_PARENT, new String(data2) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_CHILDREN, new String(data3) );
    }

result:

13:51:00.288 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /zk_demo的信息:anna2019
13:51:00.288 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /app1的信息:anna2019
13:51:00.289 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /app1/app1_1的信息:anna2020

3.3 update

public Stat setData(String path,
                    byte[] data,
                    int version)
             throws KeeperException,
                    InterruptedException
                    
Set the data for the node of the given path if such a node exists and the given version matches the version of the node (if the given version is -1, it matches any node's versions). Return the stat of the node.
This operation, if successful, will trigger all the watches on the node of the given path left by getData calls.

A KeeperException with error code KeeperException.NoNode will be thrown if no node with the given path exists.

A KeeperException with error code KeeperException.BadVersion will be thrown if the given version does not match the node's version.

The maximum allowable size of the data array is 1 MB (1,048,576 bytes). Arrays larger than this will cause a KeeperException to be thrown.

Parameters:
path - the path of the node
data - the data to set
version - the expected matching version
Returns:
the state of the node
Throws:
InterruptedException - If the server transaction is interrupted.
KeeperException - If the server signals an error with a non-zero error code.
IllegalArgumentException - if an invalid path is specified

The main note the following:

  1. Version is -1, it means that all versions of the specified path adaptation node.
  2. If the node specified path does not exist will throw KeeperException.NoNode abnormal, the node is not passed version, flip a KeeperException.BadVersion exception.
  3. byte[] data允许的最大数据量为1MB(1,048,576 bytes). If so, you will throw KeeperExecption.

run:

    @Test
    public void testGet() throws KeeperException, InterruptedException {
        byte[] data1 = zk.getData(ZNODE_PATH, false, null);
        byte[] data2 = zk.getData(ZNODE_PATH_PARENT, false, null);
        byte[] data3 = zk.getData(ZNODE_PATH_CHILDREN, false, null);
        LOGGER.info("{}的信息:{}", ZNODE_PATH, new String(data1) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_PARENT, new String(data2) );
        LOGGER.info("{}的信息:{}", ZNODE_PATH_CHILDREN, new String(data3) );
    }

The results are as follows:

13:51:00.288 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /zk_demo的信息:anna2019
13:51:00.288 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /app1的信息:anna2019
13:51:00.289 [main] INFO com.yuanrengu.demo.ZooKeeperDemo - /app1/app1_1的信息:anna2020

3.4 Delete

public void delete(String path,
                   int version)
            throws InterruptedException,
                   KeeperException
                   
Delete the node with the given path. The call will succeed if such a node exists, and the given version matches the node's version (if the given version is -1, it matches any node's versions).
A KeeperException with error code KeeperException.NoNode will be thrown if the nodes does not exist.

A KeeperException with error code KeeperException.BadVersion will be thrown if the given version does not match the node's version.

A KeeperException with error code KeeperException.NotEmpty will be thrown if the node has children.

This operation, if successful, will trigger all the watches on the node of the given path left by exists API calls, and the watches on the parent node left by getChildren API calls.

Parameters:
path - the path of the node to be deleted.
version - the expected node version.
Throws:
InterruptedException - IF the server transaction is interrupted
KeeperException - If the server signals an error with a non-zero return code.
IllegalArgumentException - if an invalid path is specified

Node may contain child nodes, delete nodes of operation there are several points to note:

  1. Version is -1, it means that all versions of the specified path adaptation node.
  2. If the node specified path does not exist KeeperException.NoNode will throw an exception, the node is not passed version, flip a KeeperException.BadVersion exception.
  3. 如果节点含有子节点,删除父节点(parent node)时会抛KeeperException.NotEmpty异常。

/ App1 has child nodes, we do the next delete operation:

    /**
     *  删除含有子节点的父节点
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void testDeleteHasChildrenZnode() throws KeeperException, InterruptedException {
        // 指定要删除的版本,-1表示删除所有版本
        zk.delete(ZNODE_PATH_PARENT, -1);
    }

You can see the log:

org.apache.zookeeper.KeeperException$NotEmptyException: KeeperErrorCode = Directory not empty for /app1

    at org.apache.zookeeper.KeeperException.create(KeeperException.java:132)
    at org.apache.zookeeper.KeeperException.create(KeeperException.java:54)
    at org.apache.zookeeper.ZooKeeper.delete(ZooKeeper.java:1793)
    at com.yuanrengu.demo.ZooKeeperDemo.testDeleteHasChildrenZnode(ZooKeeperDemo.java:89)

4 Summary

Above we realized the node add, delete, change, test, later chapters will have more fun usage, such as the implementation of distributed locks, configuration center.

Based on the above analysis, summarize a few points to note:

  1. Node has 7种形式:
  • PERSISTENT: Persistent nodes (also called permanent node), will not be automatically deleted with the end of the session.
  • PERSISTENT_SEQUENTIAL: with a monotonically increasing number of nodes lasting, will not be automatically deleted with the end of the session.
  • EPHEMERAL: temporary node will be automatically deleted with the end of the session.
  • EPHEMERAL_SEQUENTIAL: temporary node with monotonically increasing numbers, will be automatically deleted with the end of the session.
  • CONTAINER: Container node for Leader, Lock and other special purposes, when the container node any child node does not exist, the container will be the candidate node server removed sometime in the future.
  • PERSISTENT_WITH_TTL: Persistent node with TTL (time-to-live, survival time), the node has not been updated within the TTL of time and have no children, it will be automatically deleted.
  • PERSISTENT_SEQUENTIAL_WITH_TTL: With TTL (time-to-live, survival time) and lasting monotonically increasing number of nodes, the nodes are not updated within the TTL of time and have no children, it will be automatically deleted.
  1. Temporary node can not have child nodes . If you create a child node to node throw KeeperException temporary exception.
  2. Lifecycle temporary node is associated with a client session. Once the client session expires (the client and Zookeeper not necessarily disconnected session expires), then the client creates all temporary nodes will be removed .
  3. byte[] data允许的最大数据量为1MB(1,048,576 bytes)

Guess you like

Origin www.cnblogs.com/heyonggang/p/12058313.html