Zookeeper-3-client operation

Zookeeper-3-client operation

1. Common command operations

[1] View the nodes under the path

ls /路径, Only view node information

ls2 /路径, With node status information

[2] Get node data

get /路径

[3] View node status

stat /路径

[4] Create node

create /路径 数据To create a persistent node

create -s /路径 数据To create a persistent ordered node

create -e /路径 数据To create a temporary node

create -s -e /路径 数据To create a temporary ordered node

 The sequence number starts from the number of nodes under the current path, and the default is0000000000

 The name of the ordered node is the path name when it was created + the sequence number

[5] Update node data

set /路径 数据

[6] Delete node

delete /路径, Delete child nodes (no subdirectories)

rmr /路径, Delete the current node and its child nodes (subdirectories exist)

[7] Node changes under the monitoring path

ls /路径 watch

 The node has changed:

WATCHER::

WatchedEvent state:SyncConnected type:NodeChildrenChanged path:/???

 Note that once the listener event is triggered, the listener will become invalid. If you still need to listen, you still need to create a listener

[8] Monitor data changes under the node

get /路径 watch

 The data has changed:

WATCHER::

WatchedEvent state:SyncConnected type:NodeDataChanged path:/???

 Note that once the listener event is triggered, the listener will become invalid. If you still need to listen, you still need to create a listener

2. Java operation

[0] Maven dependency

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

[1] Create a client

private static final String connectString = "???.???.???.???:2181,???.???.???.???:2181,???.???.???.???:2181";
private static final int sessionTimeout = 1000 * 60 * 5; // 会话时长(5分钟)

public static void main(String[] args) {
    
    
    Watcher watcher = new Watcher() {
    
    
        @Override
        public void process(WatchedEvent event) {
    
    
            System.out.println(event.toString());
        }
    };

    ZooKeeper zooKeeper = null;
    try {
    
    
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, watcher);

        ZooKeeper.States state = zooKeeper.getState();
        System.out.println(state); // CONNECTING
    } catch (IOException e) {
    
    
        e.printStackTrace();
    } finally {
    
    
        if (null != zooKeeper) {
    
    
            try {
    
    
                zooKeeper.close();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }

}

[2] Create node

/*
 * data:byte数组允许的最大值为 1 MB (1,048,576 bytes)
 * acl:访问权限,接口常量 --> org.apache.zookeeper.ZooDefs.Ids
 * createMode:节点类型,枚举类 --> org.apache.zookeeper.CreateMode
 */
String znode = zooKeeper.create("/???", "???".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); // 没有访问限制的持久性节点
System.out.println(znode); // 返回节点路径

[3] View node

// watch:是否开启监听,如果为true,则使用创建 ZooKeeper 时,所创建的 Watcher
List<String> children = zooKeeper.getChildren("/???", false);
children.forEach(System.out::println);


CountDownLatch cd = new CountDownLatch(1);
List<String> children = zooKeeper.getChildren("/???", new Watcher() {
    
     // 使用指定的 Watcher
    @Override
    public void process(WatchedEvent event) {
    
    
        System.out.println(event.getPath() + "\t" + event.getType());
        cd.countDown();
    }
});
children.forEach(System.out::println);
cd.await();

[4] Determine whether the node exists

Stat exists = zooKeeper.exists("/???", false);
if (null != exists) {
    
    
    System.out.println(listStatMessage(exists));
} else {
    
    
    System.out.println("节点不存在!");
}

[5] Get node data

byte[] data = zooKeeper.getData("/???", false, null); // 仅获取数据
String val = new String(data, StandardCharsets.UTF_8);
System.out.println(val);


Stat stat = new Stat();
byte[] data = zooKeeper.getData("/???", false, stat); // 获取数据的同时还要查看节点状态
String val = new String(data, StandardCharsets.UTF_8);
System.out.println(val);
System.out.println(stat);

[6] View node status

StringBuilder sBuilder = new StringBuilder();
// 创建该节点的事务id
sBuilder.append("cZxid = 0x").append(Long.toHexString(stat.getCzxid())).append("\r\n");
// 创建该节点的时间(从 midnight, January 1, 1970 UTC. 至今的毫秒数)
sBuilder.append("ctime = ").append(new Date(stat.getCtime())).append("\r\n");
// 最后修改该节点的事务id
sBuilder.append("mZxid = 0x").append(Long.toHexString(stat.getMzxid())).append("\r\n");
// 最后修改该节点的时间
sBuilder.append("mtime = ").append(new Date(stat.getMtime())).append("\r\n");
// 最后修改该节点的子节点的事务id
sBuilder.append("pZxid = 0x").append(Long.toHexString(stat.getPzxid())).append("\r\n");
// 更新该节点的子节点的次数
sBuilder.append("cversion = ").append(stat.getCversion()).append("\r\n");
// 更新该节点的数据的次数
sBuilder.append("dataVersion = ").append(stat.getVersion()).append("\r\n");
// 更新该节点的访问权限的次数
sBuilder.append("aclVersion = ").append(stat.getAversion()).append("\r\n");
// 当节点是一个临时节点时,该值是此节点所属的SessionId;如果节点不是临时节点,则该值是0
sBuilder.append("ephemeralOwner = 0x").append(Long.toHexString(stat.getEphemeralOwner())).append("\r\n");
// 该节点的数据的大小
sBuilder.append("dataLength = ").append(stat.getDataLength()).append("\r\n");
// 该节点的子节点的个数
sBuilder.append("numChildren = ").append(stat.getNumChildren());
System.out.println(sBuilder.toString());

[7] Update node data

/*
 * data:byte数组允许的最大值为 1 MB (1,048,576 bytes)
 * version:数据的版本号(dataVersion),如果版本号不正确,则抛出异常 -->
 *          org.apache.zookeeper.KeeperException$BadVersionException: KeeperErrorCode = BadVersion for /???
 */
Stat stat = zooKeeper.setData("/???", "???".getBytes(), ???);
System.out.println(stat);

[8] Delete node

/*
 * 如果存在子节点,则会抛出异常 -->
 * org.apache.zookeeper.KeeperException$NotEmptyException: KeeperErrorCode = Directory not empty for /???
 *
 * version:数据的版本号(dataVersion),如果版本号不正确,则抛出异常 -->
 *          org.apache.zookeeper.KeeperException$BadVersionException: KeeperErrorCode = BadVersion for /???
 */
zooKeeper.delete("/???", ???);
System.out.println("删除成功!");

[9] Recursively delete nodes

public static void rmr(final ZooKeeper zooKeeper, final String path) throws KeeperException, InterruptedException {
    
    
    List<String> children = zooKeeper.getChildren(path, false);
    if (children.isEmpty()) {
    
    
        delete(zooKeeper, path);
        return;
    }
    for (int i = 0, size = children.size(); i < size; i++) {
    
    
        String childPath = path + "/" + children.get(i);
        rmr(zooKeeper, childPath);
    }
    delete(zooKeeper, path);
}

public static void delete(final ZooKeeper zooKeeper, final String path) throws KeeperException, InterruptedException {
    
    
    Stat stat = new Stat();
    zooKeeper.getData(path, false, stat);
    int version = stat.getVersion(); // 获取最新的数据版本号
    zooKeeper.delete(path, version);
    System.out.println("delete ==> " + path + " (" + version + ")");
}

Guess you like

Origin blog.csdn.net/adsl624153/article/details/100190127