java原生客户端
增加依赖
org.apache.zookeeper zookeeper 3.4.8
获取连接方式
public class CreateSessionDemo {
//连接信息,如果是集群可以直接使用,隔离进行拼串
private static final String CONNECTIONS = "113.140.81.67:18081";
private static final CountDownLatch countDownLatch = new CountDownLatch(1);
public static void main(String[] args) throws IOException, InterruptedException {
ZooKeeper zooKeeper = new ZooKeeper(CONNECTIONS, 5000, new Watcher() {
public void process(WatchedEvent watchedEvent) {
if (watchedEvent.getState()== Event.KeeperState.SyncConnected){
System.out.println(watchedEvent.getState());
countDownLatch.countDown();
}
}
});
countDownLatch.await();
System.out.println(zooKeeper.getState());
}
}
基本操作
public class ApiDemo {
private static final String CONNECTIONS = "113.140.81.67:18081";
private static final CountDownLatch countDownLatch = new CountDownLatch(1);
public static void main(String[] args) throws InterruptedException, KeeperException, IOException {
ZooKeeper zooKeeper = new ZooKeeper(CONNECTIONS,5000,new MyWatcher(countDownLatch));
countDownLatch.await();
System.out.println(zooKeeper.getState());
ACL acl = new ACL(ZooDefs.Perms.ALL,new Id("id","113.140.81.67"));
List<ACL> acls = new ArrayList<ACL>();
String nodePath="/demoapi";
Stat exists = zooKeeper.exists(nodePath, true);
if (exists!=null) { //判断是否存在
zooKeeper.delete(nodePath,-1);
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
String path1 = zooKeeper.create(nodePath, "2323".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("创建节点===========:"+path1);
TimeUnit.SECONDS.sleep(2);
String pp = zooKeeper.create(nodePath + "/node1-1", "node1-1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("创建子节点=========:"+pp);
TimeUnit.SECONDS.sleep(2);
byte[] data1 = zooKeeper.getData(nodePath, new MyWatcher(countDownLatch), new Stat());
System.out.println("节点内容==========:"+data1.toString());
TimeUnit.SECONDS.sleep(2);
Stat stat = zooKeeper.setData(nodePath, "ddd".getBytes(), -1);
System.out.println(stat.toString());
TimeUnit.SECONDS.sleep(2);
byte[] data = zooKeeper.getData(nodePath, new MyWatcher(countDownLatch), new Stat());
System.out.println("节点修改后的内容=======:"+data.toString());
TimeUnit.SECONDS.sleep(2);
//创建子节点
String pp1=zooKeeper.create(nodePath+"/dd","wefwef".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
System.out.println("创建的子节点========:"+pp1);
TimeUnit.SECONDS.sleep(1);
//修改子节点
zooKeeper.setData(nodePath+"/dd","wfwef".getBytes(), -1);
TimeUnit.SECONDS.sleep(1);
List<String> children = zooKeeper.getChildren(nodePath, true);
System.out.println(children);
}
}
}