Java客户端连接zookeeper


Java客户端连接zookeeper

导入依赖


    org.apache.zookeeper
    zookeeper
    3.5.7

测试类

package com.yl.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * zookeeper客户端测试
 *
 * @author Y-wee
 */
public class ZkClient {
    /**
     * zookeeper集群多个服务器之间用逗号隔开
     */
    private static String connectString = "192.168.84.136:2181,192.168.84.137:2181,192.168.84.138:2181";
    /**
     * 会话超时时间,不要设置太小
     * 如果此值小于zookeeper的创建时间则当zookeeper还未来得及创建连接,会话时间已到
     * 则抛出异常:org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /znode2
     * 注意关闭防火墙
     */
    private int sessionTimeout = 170000;

    private ZooKeeper zooKeeper;

    /**
     * 初始化方法:创建ZooKeeper连接
     *
     * @throws IOException
     */
    @Before
    public void init() throws IOException {
        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

            }
        });
    }

    /**
     * 创建节点
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void createNode() throws KeeperException, InterruptedException {
        /**
         * 第一个参数:节点
         * 第二个参数:节点值
         * 第三个参数:节点访问权限
         * 第四个参数:节点类型
         */
        zooKeeper.create("/znode3", "v3".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    /**
     * 获取子节点
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void getNodeChildren() throws KeeperException, InterruptedException {
        /**
         * 第一个参数:节点路径
         * 第二参数:是否开启监听
         */
        List childrens = zooKeeper.getChildren("/", false);
        childrens.forEach(System.out::println);
    }

    /**
     * 判断节点是否存在
     */
    @Test
    public void existNode() throws KeeperException, InterruptedException {
        Stat stat = zooKeeper.exists("/znode1", false);
        System.out.println(stat == null ? "not exist" : "exist");
    }

}