Zookeeper Java API的使用

本文介绍Zookeeper Java API的使用


引入相应Jar包

  • bulidPath

    解压下载的zookeeper-3.4.9.tar.gz的根目录就有相应jar

zookeeper-3.4.9.jar

在eclipse的buildPath里引入zookeeper-3.4.9.jar

  • maven构建的项目
    若是maven构建的项目,加入以下依赖
<dependency>
    <groupId>org.apache.zookeepergroupId>
    <artifactId>zookeeperartifactId>
    <version>3.4.9version>
dependency>

1、连接

String connectionString = "127.0.0.1:2181";
int sessionTimeout = 30000;
ZooKeeper zk = new ZooKeeper(connectionString,sessionTimeout,null
});
  • connectionString是连接信息,当为集群的时候,使用”,”分隔,如
    “192.168.1.1:2181,192.168.1.2:2181”
  • sessionTimeout指会话过期时间,其值minSessionTimeout最小为tickTime的2倍,最大值 maxSessionTimeout为tickTime的20倍;即使传入的值不在此范围实际起作用的也是minSessionTimeout至maxSessionTimeout

2、创建节点

zk.create("/testRoot", "testRoot".getBytes(), 
           ZooDefs.Ids.OPEN_ACL_UNSAFE, 
           CreateMode.PERSISTENT);
类型 描述
CreateMode.PERSISTENT 永久性节点
CreateMode.PERSISTENT_SEQUENTIAL 永久性序列节点
CreateMode.EPHEMERAL 临时节点,会话断开或过期时会删除此节点
CreateMode.PERSISTENT_SEQUENTIAL 临时序列节点,会话断开或过期时会删除此节点

3、获取节点

Stat stat = new Stat();
zk.getData("/testRoot",true,stat);

4、修改节点数据

// -1表示忽略版本
zk.setData("/testRoot", "testRoot_modified".getBytes(), -1);

5、创建子节点

zk.create("/testRoot/child1", 
            "child1_data".getBytes(), 
            ZooDefs.Ids.OPEN_ACL_UNSAFE, 
            CreateMode.PERSISTENT);

6、获取子节点

    List children = zk.getChildren("/testRoot",new Watcher() {
        public void process(WatchedEvent event) {
            System.out.println("this is children node event");
            System.out.println(event);
        }
    });

注:getChildren方法会在子点有变化时触发Watcher()这个监听器


7、删除节点

zk.delete("/testRoot", -1);
zk.delete("/testRoot/child1", -1);

8、关闭连连接

zk.close();

注:一般情况下close()方法放在finally代码块执行


关于KeeperErrorCode = ConnectionLoss错误

在使用Zookeeper API时,常常会引发以下错误 ,这是由于连接还未完成就执行zookeeper的get/create/exists操作引起的

Exception in thread "main" org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /test
at org.apache.zookeeper.KeeperException.create(KeeperException.Java:99)
at org.apache.zookeeper.KeeperException.create(KeeperException.java:51)
at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1501)
at org.apache.zookeeper.ZooKeeper.exists(ZooKeeper.java:1529)
at com.jiq.test.ZooKeeperTest.main(ZooKeeperTest.java:12)

解决的办法是等Zookeeper连接初始化完成再使用实例,以下是示例代码

    public static ZooKeeper getInstance() throws IOException, InterruptedException {  
        //--------------------------------------------------------------  
        // 为避免连接还未完成就执行zookeeper的get/create/exists操作引起的(KeeperErrorCode = ConnectionLoss)  
        // 这里等Zookeeper的连接完成才返回实例  
        //--------------------------------------------------------------  
        final CountDownLatch connectedSignal = new CountDownLatch(1);  
        ZooKeeper zk = new ZooKeeper(connectionString, sessionTimeout, new Watcher() {  
             @Override  
             public void process(WatchedEvent event) {  
                 if  (event.getState()  ==  Event.KeeperState.SyncConnected) {  
                     connectedSignal.countDown();  
                 }  
             }  
         });  
        connectedSignal.await();  
        return zk;  
    }  

注:Zookeeper的监控只有在使用getData(),exists(),getChildren()这几个方法时才会触发watcher

你可能感兴趣的:(zookeeper,java)