已复制
全屏展示
复制代码

zookeeper Java API 客户端

· 1 min read

一. pom.xml

添加 Maven 依赖

<dependencies>
  <dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>4.0.0</version>
  </dependency>
  <dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>4.0.0</version>
  </dependency>
</dependencies>

二. 常用接口

主程序

package org.example;


import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.List;


public class Main {
    public static void main(String[] args) throws Exception {
        zookeeperClient();
    }

    public static void zookeeperClient() throws Exception {

        CuratorFramework client = CuratorFrameworkFactory
                .builder()
                .connectString("node1:2181,node2:2181,node3:2181")
                .sessionTimeoutMs(4000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("")
                .build();
        client.start();

        byte[] bytes;
        Stat stat = new Stat();

        // 创建节点
        client.create()
                .withMode(CreateMode.PERSISTENT)
                .forPath("/test-node", "mydata".getBytes());
        client.create()
                .withMode(CreateMode.PERSISTENT)
                .forPath("/test-node/child1", "mydata-child1".getBytes());

        // 查询节点数据
        bytes = client
                .getData()
                .storingStatIn(stat)
                .forPath("/test-node");
        System.out.println("data = " + new String(bytes));
        System.out.println("stat.getVersion = " + stat.getVersion());


        // 获取所有子节点
        List<String> children = client.getChildren().forPath("/test-node");
        System.out.println("children = " + children);


        // 更新节点
        client.setData()
                .forPath("/test-node", "mydatanew".getBytes());
        bytes = client
                .getData()
                .storingStatIn(stat)
                .forPath("/test-node");
        System.out.println("data = " + new String(bytes));
        System.out.println("stat.getVersion = " + stat.getVersion());

        // 删除节点
        client.delete()
                .deletingChildrenIfNeeded()
                .forPath("/test-node");

        // 判断是否存在
        Stat stat_exists = client.checkExists()
                .forPath("/test-node");
        boolean exists = stat_exists != null;
        System.out.println("exists: " + exists);
        System.out.println("stat_exists = " + stat_exists);

        client.close();
    }

}
🔗

文章推荐