bulidPath
解压下载的zookeeper-3.4.9.tar.gz的根目录就有相应jar
zookeeper-3.4.9.jar
在eclipse的buildPath里引入zookeeper-3.4.9.jar
<dependency>
<groupId>org.apache.zookeepergroupId>
<artifactId>zookeeperartifactId>
<version>3.4.9version>
dependency>
String connectionString = "127.0.0.1:2181";
int sessionTimeout = 30000;
ZooKeeper zk = new ZooKeeper(connectionString,sessionTimeout,null
});
zk.create("/testRoot", "testRoot".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
类型 | 描述 |
---|---|
CreateMode.PERSISTENT | 永久性节点 |
CreateMode.PERSISTENT_SEQUENTIAL | 永久性序列节点 |
CreateMode.EPHEMERAL | 临时节点,会话断开或过期时会删除此节点 |
CreateMode.PERSISTENT_SEQUENTIAL | 临时序列节点,会话断开或过期时会删除此节点 |
Stat stat = new Stat();
zk.getData("/testRoot",true,stat);
// -1表示忽略版本
zk.setData("/testRoot", "testRoot_modified".getBytes(), -1);
zk.create("/testRoot/child1",
"child1_data".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
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()这个监听器
zk.delete("/testRoot", -1);
zk.delete("/testRoot/child1", -1);
zk.close();
注:一般情况下close()方法放在finally代码块执行
在使用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