- 创建节点
- watch
我们使用ZooKeeper官方java客户端进行测试,另外可以使用curator.
我们使用Maven添加相关依赖
1 2 3 4 5
| <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.8</version> </dependency>
|
创建节点
然后我们向zk服务器上添加俩个节点
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper;
import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit;
public class CreateNode { private static final String ROOT_PATH = "/Servers"; private static ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, KeeperException, InterruptedException { zooKeeper = new ZooKeeper("localhost:2181", 15000, event -> { });
zooKeeper.create(ROOT_PATH, "create".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { }, ROOT_PATH);
zooKeeper.create(ROOT_PATH + "/server1", "create".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { }, ROOT_PATH);
List<String> children = zooKeeper.getChildren(ROOT_PATH, event -> { });
children.forEach(child -> System.out.println(child));
TimeUnit.SECONDS.sleep(1); } }
|
watch
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| import org.apache.zookeeper.*;
import java.io.IOException; import java.util.Random; import java.util.concurrent.TimeUnit;
public class CreateNode { private static final String ROOT_PATH = "/Servers" + new Random().nextInt(100000); private static ZooKeeper zooKeeper;
public static void main(String[] args) throws IOException, KeeperException, InterruptedException { zooKeeper = new ZooKeeper("localhost:2181", 15000, event -> { System.out.println("事件变化 : " + event.getPath() + " -> " + event.getType()); });
zooKeeper.create(ROOT_PATH, "create".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { try { System.out.println("Create Node OK!"); zooKeeper.getChildren(ROOT_PATH, event -> { System.out.println("Watch : " + event.getPath() + " -> " + event.getType()); }); } catch (final Exception e) { e.printStackTrace(); } }, ROOT_PATH);
TimeUnit.SECONDS.sleep(3);
zooKeeper.create(ROOT_PATH + "/server1", "create".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT, (rc, path, ctx, name) -> { try { System.out.println("Create Node OK!"); zooKeeper.getChildren(ROOT_PATH, event -> { System.out.println("Watch : " + event.getPath() + " -> " + event.getType()); }); } catch (final Exception e) { e.printStackTrace(); } }, ROOT_PATH);
TimeUnit.SECONDS.sleep(3); } }
|
输出结果为
1 2 3 4
| 事件变化 : null -> None Create Node OK! Watch : /Servers53734 -> NodeChildrenChanged Create Node OK!
|