zookeepr的常用javaapi

一.常用的JAVA API
增删改查与监听 也可用./zkCli.sh打开命令行模式操作

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

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

public class SimpleZkClient {

    private static final String connectString = "master:2181,slave2:2181";
    private static final int sessionTimeout = 2000;

    ZooKeeper zooKeeper = null;

    @Before
    public void init() throws IOException{

        zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {			 **//接受处理事件**
                System.out.println(watchedEvent.getType()+"---"+watchedEvent.getPath()+"---"+watchedEvent.toString());
                try {
                    getChildren();							//处理完成事件之后本次监听结束 所以需要再次调用
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


    }
    public void testCreate() throws KeeperException, InterruptedException {			//创建节点   可以传入任意类型的数据,但需要是字节数组形式
        String nodeCreated = zooKeeper.create("/testjava", "hellozk".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }

    @Test
    public void getChildren() throws KeeperException, InterruptedException {				//获取子节点
        List<String> children = zooKeeper.getChildren("/",true);
        for(String chlid : children){
            System.out.println(chlid);
        }
    }

    @Test
    public void testNodeExists() throws KeeperException, InterruptedException {			//测试节点是否存在
        //metadata
        Stat stat = zooKeeper.exists("/testjava",false);
        System.out.println(stat);
        System.out.println(stat==null?"not exists":"exists");
    }

    @Test
    public void getData() throws KeeperException, InterruptedException, UnsupportedEncodingException {			//获取节点的数据
        byte[] data = zooKeeper.getData("/testjava",false, null);
        System.out.println(new String(data,"utf-8"));
        //isntance
        // Object data = zooKeeper.getData("/testjaav",false, null)
    }
}

二.单元测试简介
文中代码的@为单元测试框架junit
可以进行代码块部分的测试而不用取创建main函数
1.@Test: 测试方法

	2.@Ignore: 被忽略的测试方法:加上之后,暂时不运行此段代码

3.@Before: 每一个测试方法之前运行

4.@After: 每一个测试方法之后运行

5.@BeforeClass: 方法必须必须要是静态方法(static 声明),所有测试开始之前运行,注意区分before,是所有测试方法

6.@AfterClass: 方法必须要是静态方法(static 声明),所有测试结束之后运行,注意区分 @After

三.程序运行流程简介在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值