zookeeper01

package com.atguigu.zk;

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

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

/**
 * @auther :atom
 * @date :2022/2/12 22:21
 */
public class ZkClient {
    private static String connectionString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";//host配置完
    private int sessionTimeout = 10000;//2000毫秒
    private ZooKeeper zkClient;

    @Before
    public void init() throws IOException {
        zkClient = new ZooKeeper(connectionString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
/*                List<String> children = null;
                System.out.println("==============================");
                try {
                    children = zkClient.getChildren("/", true);
                    for (String child : children) {
                        System.out.println(child);
                    }
                    System.out.println("=============================");

                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }*/

            }
        });
    }

    @Test
    public void create() throws KeeperException, InterruptedException {
        String clientCreated = zkClient.create("/atguigu", "ss.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zkClient.getChildren("/", true);
        for (String child : children) {
            System.out.println(child);
        }
        Thread.sleep(Long.MAX_VALUE);
    }

    @Test
    public void isExist() throws KeeperException, InterruptedException {
        Stat exists = zkClient.exists("/atguigu", false);
        System.out.println(exists == null ? "not exist" : "exist");
    }


    //关闭客户端对象
    @After
    public void close() throws InterruptedException {
        zkClient.close();
    }
}


posted @ 2022-02-13 00:28  ftwftw  阅读(45)  评论(0)    收藏  举报