zookeper 移步创建节点
rc状态说明:
0:接口调用成功
-4:服务端和客户端断开链接
-110:几点已经存在
-112:会话已经过期
package com.chongshi.test;
import java.io.IOException;
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.AsyncCallback.StringCallback;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.w3c.dom.ProcessingInstruction;
public class ZKTest {
static ZooKeeper zk = null;
static CountDownLatch cdl = new CountDownLatch(1);
static CountDownLatch cdl1 = new CountDownLatch(1);
static {
try {
zk = new ZooKeeper("127.0.0.1:2181", 1000, new MyWatcher(cdl));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws KeeperException {
try {
cdl.await();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
zk.create("/s1", "test".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT, new MyStringCallback(cdl1),
"Hello World");
try {
cdl1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class MyStringCallback implements StringCallback {
private CountDownLatch countDownLatch;
public MyStringCallback(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
public void processResult(int rc, String path, Object ctx, String name) {
System.err.println(rc);
countDownLatch.countDown();
}
}
class MyWatcher implements Watcher {
private CountDownLatch countDownLatch;
public MyWatcher(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
public void process(WatchedEvent event) {
if (event.getState() == KeeperState.SyncConnected) {
System.err.println("连接上");
countDownLatch.countDown();
}
}
}