1. 程式人生 > 其它 >Java客戶端連線zookeeper

Java客戶端連線zookeeper

Java客戶端連線zookeeper

匯入依賴

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

測試類

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<String> 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");
    }

}