Zookeeper基础知识-java调用客户端

Zookeeper基础知识-java调用客户端,第1张

Zookeeper基础知识-java调用客户端

1)创建一个工程:Zookeeper

2)添加pom文件(Zookeeper,log4j)


     log4j
     log4j
     1.2.12

 
     org.apache.zookeeper
     zookeeper
     3.7.0
 

3)log4j.properties文件文件放在项目的根目录下

4)创建包和类

private String connectString="172.29.97.56:2181,172.29.97.56:2182,172.29.97.56:2183";
    int  sessionTimeout =1000;
    public ZooKeeper ckClient;

    @BeforeEach
    public void init() throws IOException, KeeperException, InterruptedException {
            ckClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                List children = null;
                try {
                    children = ckClient.getChildren("/china",true);
                    for (String child:children) {
                        System.out.println(child);
                    }
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                
            }
        });
        //ConNECTED
        Thread.sleep(1000);
        System.out.println(ckClient.getState());
    }

    @Test
    public void create() throws KeeperException, InterruptedException {
        String nodeCreated=ckClient.create("/china/beijing","beijing".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    }

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

注意点:1.在其它案例执行前执行,使用junit5的@BeforeEach注解,junit4的是@Before注解,使用不对的话,会导致注解失效。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5635903.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存