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

1)创建一个工程:Zookeeper

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

<dependency>
     <groupId>log4j</groupId>
     <artifactId>log4j</artifactId>
     <version>1.2.12</version>
</dependency>
 <dependency>
     <groupId>org.apache.zookeeper</groupId>
     <artifactId>zookeeper</artifactId>
     <version>3.7.0</version>
 </dependency>

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<String> 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<String> children = ckClient.getChildren("/china",true);
        for (String child:children) {
            System.out.println(child);
        }
        //延迟
        Thread.sleep(Long.MAX_VALUE);
    }

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值