Java代码连接ZooKeeper(Curator)

Java代码连接ZooKeeper(Curator)

leo 742 2021-04-10

Curator简介

Apache Curator 是 ZooKeeper 的Java客户端库。包含了高标准的API工具库,让我们可以更加简单、可靠的使用ZooKeeper。

创建项目

先启动ZooKeeper。如果还没安装:docker-compose安装ZooKeeper集群

通过IDEA创建一个Maven项目。并引入如下依赖:

<!-- curator begin -->
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-framework</artifactId>
    <version>4.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>4.2.0</version>
</dependency>
<!-- curator end -->
<!-- junit begin -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>
<!-- junit end -->

创建junit测试类

package top.zysite;

import org.apache.curator.RetryPolicy;
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.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * @author Leo
 * @create 2020/11/16 14:56
 **/
public class ZookeeperTests {


    private static final int BASE_SLEEP_TIME = 1000;
    private static final int MAX_RETRIES = 3;

    private CuratorFramework zkClient;
    @Before
    public void connect(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES);
        zkClient = CuratorFrameworkFactory.builder()
                //服务器地址,可以为多个
                .connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183")
                .retryPolicy(retryPolicy)
                .build();
        zkClient.start();
    }
    @Test
    public void create() throws Exception {
//        zkClient.create().forPath("/parentNode");
        //父节点不存在时创建父节点
        zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/parentNode/node1");
        zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/parentNode/node2");
        System.out.println(zkClient.checkExists().forPath("/parentNode/node1"));
        System.out.println(zkClient.checkExists().forPath("/parentNode/node2"));
    }

    @Test
    public void delete() throws Exception {
        zkClient.delete().forPath("/parentNode/node1");
    }

    @Test
    public void update() throws Exception {
        zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath("/parentNode/node1", "this is data of node1".getBytes());
        System.out.println(zkClient.getData().forPath("/parentNode/node1"));

        zkClient.setData().forPath("/parentNode/node1", "update data of node1".getBytes());
    }


    @Test
    public void getAllData() throws Exception {
        //获取所有孩子节点路径
        List<String> childrenPaths = zkClient.getChildren().forPath("/parentNode");
        childrenPaths.forEach(System.out::println);
    }
}

API文档