<dependencies> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.5.5</version> </dependency> </dependencies>
public class MyZookeeper implements Watcher { private static CountDownLatch latch = new CountDownLatch(1); public static void main(String[] args) { try { ZooKeeper zooKeeper = new ZooKeeper("192.168.1.102:2181", 5000, new MyZookeeper()); System.out.println(zooKeeper.getState()); try { latch.await(); } catch (InterruptedException e) { } System.out.println("zookeeper session established"); } catch (IOException e) { } } @Override public void process(WatchedEvent event) { System.out.println("Receive watched event:" + event); if (KeeperState.SyncConnected == event.getState()) { latch.countDown(); } } }
zooKeeper.create("/zk-1", "hello".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
zooKeeper.delete("/zk-book", -1);
zooKeeper.delete("/zk-book", -1, (int rc, String path, Object context) -> { System.out.printf("rc = %d/npath = %s/ncontext = %s/n", rc, path, path, context.toString()); }, "I am context data"); Thread.sleep(3000);
List<String> children = zooKeeper.getChildren("/zk-book", new MyZookeeper()); children.forEach(System.out::println);
zooKeeper.getChildren("/zk-book", new MyZookeeper(), (int rc, String path, Object ctx, List<String> children, Stat stat) -> System.out.printf("rc = %d/tpath = %s/tctx = %s/tchidren = %s/tstat = %s/n", rc, path, ctx, String.join(",", children),stat.toString()), "I am callback data"); zooKeeper.create("/zk-book/zb3", "hello".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); Thread.sleep(3000);
byte[] data = zooKeeper.getData("/zk-book", new MyZookeeper(), null); System.out.println(new String(data, 0, data.length));
zooKeeper.getData("/zk-book", new MyZookeeper(), (int rc, String path, Object ctx, byte data[], Stat stat) -> {}, null); Thread.sleep(3000);
Stat stat1 = zooKeeper.setData("/zk-book", "hello".getBytes(), -1);
zooKeeper.setData("/zk-book", "hello".getBytes(), -1, (int rc, String path, Object ctx, Stat stat) ->{}, null); Thread.sleep(3000);
Stat exists = zooKeeper.exists("/zk-book", new MyZookeeper());
Watcher watcher监听 3 类事件。
zooKeeper.exists("/zk-book", new MyZookeeper(), (int rc, String path, Object ctx, Stat stat) -> {}, null);