zookeeper入门实例
package org.merit.test.zookeepertest;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
public class ZookeeperTestCase implements Watcher {
private static ZooKeeper zk;
private String path;
private Stat stat;
private static CountDownLatch countDown = new CountDownLatch(1);
public ZookeeperTestCase(){
if(zk == null){
try {
System.out.println("Starting ZK:");
zk = new ZooKeeper("0.0.0.0", 3000, this); //"0.0.0.0"服务器端IP
countDown.await();
System.out.println("Finished starting ZK: " + zk);
} catch (IOException e) {
zk = null;
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void process(WatchedEvent event) {
if(event.getState() == KeeperState.SyncConnected){
countDown.countDown();
}
System.out.println("-----"+event.getState());
}
public void create() throws KeeperException, InterruptedException{
path = zk.create("/zk_java", "java_binding".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
System.out.println("created znode:" + path);
}
public void list() throws KeeperException, InterruptedException{
List<String> strings = zk.getChildren("/", true);
System.out.println("list:"+strings);
}
public void exist() throws KeeperException, InterruptedException{
stat = zk.exists(path, true);
System.out.println("exits:"+stat.getDataLength());
}
public void get() throws KeeperException, InterruptedException{
Stat stat = new Stat();
byte[] data = zk.getData(path, true, stat);
System.out.print(new String(data));
System.out.println(stat);
}
public void set() throws KeeperException, InterruptedException{
stat = zk.setData(path, "zk_ooxx".getBytes(), stat.getVersion());
}
public void delete() throws InterruptedException, KeeperException{
zk.delete(path, stat.getVersion());
}
public void close() throws InterruptedException{
zk.close();
}
public static void main(String[] args) throws Exception {
ZookeeperTestCase zkTest = new ZookeeperTestCase();
zkTest.list();
zkTest.create();
zkTest.list();
zkTest.exist();
zkTest.get();
zkTest.set();
zkTest.get();
zkTest.delete();
zkTest.list();
zkTest.close();
}
}