znode节点创建

来源:互联网 发布:红蜘蛛教学软件介绍 编辑:程序博客网 时间:2024/04/16 17:05

原文:http://www.hollischuang.com/archives/1280

节点

Znode有四种类型,PERSISTENT(持久节点)、PERSISTENT_SEQUENTIAL(持久的连续节点)、EPHEMERAL(临时节点)、EPHEMERAL_SEQUENTIAL(临时的连续节点)

Znode的类型在创建时确定并且之后不能再修改

临时节点

临时节点的生命周期和客户端会话绑定。也就是说,如果客户端会话失效,那么这个节点就会自动被清除掉。

String root = "/ephemeral";String createdPath = zk.create(root, root.getBytes(),          Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println("createdPath = " + createdPath);String path = "/ephemeral/test01" ; createdPath = zk.create(path, path.getBytes(),            Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);System.out.println("createdPath = " + createdPath);Thread.sleep(1000 * 20); // 等待20秒关闭ZooKeeper连接zk.close(); // 关闭连接后创建的临时节点将自动删除

临时节点不能有子节点

持久节点

所谓持久节点,是指在节点创建后,就一直存在,直到有删除操作来主动清除这个节点——不会因为创建该节点的客户端会话失效而消失。

String root = "/computer";String createdPath = zk.create(root, root.getBytes(),       Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println("createdPath = " + createdPath);

临时顺序节点

临时节点的生命周期和客户端会话绑定。也就是说,如果客户端会话失效,那么这个节点就会自动被清除掉。注意创建的节点会自动加上编号。

String root = "/ephemeral";String createdPath = zk.create(root, root.getBytes(),          Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println("createdPath = " + createdPath);String path = "/ephemeral/test01" ; createdPath = zk.create(path, path.getBytes(),            Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);System.out.println("createdPath = " + createdPath);Thread.sleep(1000 * 20); // 等待20秒关闭ZooKeeper连接zk.close(); // 关闭连接后创建的临时节点将自动删除

输出结果:

type = NonecreatedPath = /ephemeral/test0000000003createdPath = /ephemeral/test0000000004createdPath = /ephemeral/test0000000005createdPath = /ephemeral/test0000000006

持久顺序节点

这类节点的基本特性和持久节点类型是一致的。额外的特性是,在ZooKeeper中,每个父节点会为他的第一级子节点维护一份时序,会记录每个子节点创建的先后顺序。基于这个特性,在创建子节点的时候,可以设置这个属性,那么在创建节点过程中,ZooKeeper会自动为给定节点名加上一个数字后缀,作为新的节点名。这个数字后缀的范围是整型的最大值。

String root = "/computer";String createdPath = zk.create(root, root.getBytes(),       Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println("createdPath = " + createdPath);for (int i=0; i<5; i++) {   String path = "/computer/node";   String createdPath = zk.create(path, path.getBytes(),       Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);   System.out.println("createdPath = " + createdPath);}zk.close();

运行结果:

createdPath = /computercreatedPath = /computer/node0000000000createdPath = /computer/node0000000001createdPath = /computer/node0000000002createdPath = /computer/node0000000003createdPath = /computer/node0000000004结果中的0000000000~0000000004都是自动添加的序列号

节点中除了可以存储数据,还包含状态信息。


原创粉丝点击