黑猴子的家: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 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);
}

你可能感兴趣的:(黑猴子的家:Zookeeper Java API)