黑猴子的家:Zookeeper Java API

1、Code -> GitHub

https://github.com/liufengji/zookeeper_code.git

2、环境准备

1)创建一个工程
2)解压zookeeper-3.4.10.tar.gz文件
3)拷贝zookeeper-3.4.10.jar、jline-0.9.94.jar、log4j-1.2.16.jar、netty-3.10.5.Final.jar、slf4j-api-1.6.1.jar、slf4j-log4j12-1.6.1.jar到工程的lib目录。并build一下,导入工程。
4)拷贝log4j.properties文件到项目src根目录

3、创建ZooKeeper客户端

private String connectString = "node1:2181,node2:2181,node3:2181";
private int sessionTimeout = 2000;
ZooKeeper zkClient;

// 初始化方法
@Before
public void initzk() throws IOException {
    zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            System.out.println(event.getType() + "\t" + event.getPath());
            // 判断节点是否存在
            Stat exists;
            try {
                exists = zkClient.exists("/victor", true);
                System.out.println(exists == null?"not exist ":"exist");
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
}

4、创建子节点

// 创建子节点
@Test
public void createNode() throws KeeperException, InterruptedException{
            // 参数1:节点创建路径
            // 参数2:节点存放的数据
            // 参数3:权限
            // 参数4:节点类型
            String create = zkClient.create("/victor",
                "haohaoxuexi".getBytes(),
                Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
            System.out.println(create);
}

5、获取子节点并监听

// 获取子节点
@Test
public void getNode() throws KeeperException, InterruptedException{
    // 参数1:节点路径
    // 参数2:是否监听
    List<String> children = zkClient.getChildren("/", true);
        
    for (String node : children) {
        System.out.println(node);
    }

    // 延时阻塞
    Thread.sleep(Long.MAX_VALUE);
}

6、判断znode是否存在

// 判断节点是否存在
@Test
public void isexist() throws KeeperException, InterruptedException{

            Stat exists = zkClient.exists("/victor", true);
        
            System.out.println(exists == null?"not exist ":"exist");
        
            Thread.sleep(Long.MAX_VALUE);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值