ZooKeeper JavaAPI 操作

3.1 pom.xml引入

  1. <dependency>
  2. <groupId>junit</groupId>
  3. <artifactId>junit</artifactId>
  4. <version>4.10</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <!--curator-->
  8. <dependency>
  9. <groupId>org.apache.curator</groupId>
  10. <artifactId>curator-framework</artifactId>
  11. <version>4.0.0</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.apache.curator</groupId>
  15. <artifactId>curator-recipes</artifactId>
  16. <version>4.0.0</version>
  17. </dependency>![点击并拖拽以移动](data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==)

3.2 创建连接【命令:./zkCli.sh –server ip:port】

  1. @Test
  2. public void testConnection() {
  3. // 第一种方式
  4. CuratorFramework newClient = CuratorFrameworkFactory.newClient("192.168.135.20:2181",
  5. 60 * 1000, 15 * 1000,
  6. new ExponentialBackoffRetry(3000, 10));
  7. // 第二种方式
  8. CuratorFramework client = CuratorFrameworkFactory.builder().
  9. connectString("192.168.135.20:2181") // 服务端
  10. .sessionTimeoutMs(60 * 1000) // session失效时间
  11. .connectionTimeoutMs(15 * 1000) // 连接最大时间
  12. .retryPolicy(new ExponentialBackoffRetry(3000, 10)) // 重试策略
  13. .namespace("hikktn") // 客户端名称
  14. .build();
  15. // 开启连接
  16. client.start();
  17. }

3.3 创建节点【命令:create /节点path】

  1. @Test
  2. public void testCreate(){
  3. try {
  4. // 如果没有指定数据,默认将客户端ip作为节点内容
  5. String path = client.create().forPath("/app1");
  6. System.out.println(path);
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. }

3.4 创建节点加内容【命令:create /节点path value】

  1. @Test
  2. public void testCreate2(){
  3. try {
  4. // 创建节点和内容
  5. String path = client.create().forPath("/app1","hikktn2".getBytes());
  6. System.out.println(path);
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. }

3.5创建节点类型 【命令:create -e /节点path】

  1. (持久化节点,临时节点,顺序节点)
  1. @Test
  2. public void testCreate3(){
  3. try {
  4. // 设置节点类型 -- CreateMode 枚举类,选择什么关键字就是什么类型节点,持久化节点,临时节点
  5. String path = client.create().withMode(CreateMode.EPHEMERAL).forPath("/app1");
  6. System.out.println(path);
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. }

3.6 创建多级节点 【命令:create /父节点path create /子节点path】

  1. 可以不再像命令执行一样,先创建父节点,再来创建子节点
  1. @Test
  2. public void testCreate4(){
  3. try {
  4. // 创建多级节点
  5. // 如果父节点不存在,则创建父节点
  6. String path = client.create().creatingParentsIfNeeded().forPath("/app1/h1");
  7. System.out.println(path);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }

3.7 查询节点 【命令:get /节点path】

  1. @Test
  2. public void testGet1(){
  3. try {
  4. // 查询节点 get
  5. byte[] bytes = client.getData().forPath("/app1");
  6. System.out.println(new String(bytes));
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. }

3.8 查询子节点【命令:ls】

  1. @Test
  2. public void testGet2(){
  3. try {
  4. // 查询子节点 ls
  5. List<String> list = client.getChildren().forPath("/app1");
  6. System.out.println(list);
  7. } catch (Exception e) {
  8. e.printStackTrace();
  9. }
  10. }

3.9 查询节点状态信息 【命令:ls -s】

  1. @Test
  2. public void testGet3(){
  3. try {
  4. // 查询节点状态信息 ls -s
  5. Stat stat =new Stat();
  6. byte[] bytes = client.getData().storingStatIn(stat).forPath("/app1");
  7. System.out.println(new String(bytes));
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }
  11. }

3.10 修改节点内容【命令:set /节点path value】

  1. @Test
  2. public void testSet1(){
  3. try {
  4. Stat stat = client.setData().forPath("/app1", "hehe".getBytes());
  5. System.out.println(stat);
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. }
  9. }

3.11 锁定节点后,进行修改节点【命令:stat /节点path [watch] set /节点path value [version]】

  1. @Test
  2. public void testSet2(){
  3. try {
  4. Stat status = new Stat();
  5. //3. 查询节点状态信息:ls -s
  6. client.getData().storingStatIn(status).forPath("/app1");
  7. int version = status.getVersion();//查询出来的 3
  8. System.out.println(version);
  9. client.setData().withVersion(version).forPath("/app1", "hehe".getBytes());
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }

3.12 删除节点【命令:delete /节点path】

  1. @Test
  2. public void testDelete() throws Exception {
  3. // 1. 删除单个节点
  4. client.delete().forPath("/app1");
  5. }

3.13 删除带有子节点的节点【命令:deleteall /节点path】

  1. @Test
  2. public void testDelete2() throws Exception {
  3. //2. 删除带有子节点的节点
  4. client.delete().deletingChildrenIfNeeded().forPath("/app4");
  5. }

3.14 必须成功删除节点

  1. @Test
  2. public void testDelete3() throws Exception {
  3. //3. 必须成功的删除
  4. client.delete().guaranteed().forPath("/app2");
  5. }

3.15 删除成功后的回调方法

  1. @Test
  2. public void testDelete4() throws Exception {
  3. //4. 回调
  4. client.delete().guaranteed().inBackground(new BackgroundCallback() {
  5. @Override
  6. public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
  7. System.out.println("我被删除了~");
  8. System.out.println(event);
  9. }
  10. }).forPath("/app1");
  11. }

4 Zookeeper JavaAPI操作-Watch监听概述

•NodeCache : 只是监听某一个特定的节点

•PathChildrenCache : 监控一个ZNode的子节点.

•TreeCache : 可以监控整个树上的所有节点,类似于PathChildrenCache和NodeCache的组合

4.1 监听一个节点注册,当父节点新增父节点的情况,附带一些操作

  1. /**
  2. * 演示 NodeCache:给指定一个节点注册监听器
  3. */
  4. @Test
  5. public void testNodeCache() throws Exception {
  6. //1. 创建NodeCache对象
  7. final NodeCache nodeCache = new NodeCache(client, "/app1");
  8. //2. 注册监听
  9. nodeCache.getListenable().addListener(new NodeCacheListener() {
  10. @Override
  11. public void nodeChanged() throws Exception {
  12. System.out.println("节点变化了~");
  13. //获取修改节点后的数据
  14. byte[] data = nodeCache.getCurrentData().getData();
  15. System.out.println(new String(data));
  16. }
  17. });
  18. //3. 开启监听.如果设置为true,则开启监听是,加载缓冲数据
  19. nodeCache.start(true);
  20. while (true) {
  21. }
  22. }

4.2 监听一个节点注册,监听父节点下的所有子节点变化

  1. @Test
  2. public void testPathChildrenCache() throws Exception {
  3. //1.创建监听对象
  4. PathChildrenCache pathChildrenCache = new PathChildrenCache(client, "/app2", true);
  5. //2. 绑定监听器
  6. pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
  7. @Override
  8. public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
  9. System.out.println("子节点变化了~");
  10. System.out.println(event);
  11. //监听子节点的数据变更,并且拿到变更后的数据
  12. //1.获取类型
  13. PathChildrenCacheEvent.Type type = event.getType();
  14. //2.判断类型是否是update
  15. if (type.equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)) {
  16. System.out.println("数据变了!!!");
  17. byte[] data = event.getData().getData();
  18. System.out.println(new String(data));
  19. }
  20. }
  21. });
  22. //3. 开启
  23. pathChildrenCache.start();
  24. while (true) {
  25. }
  26. }

4.3 监听一个节点注册,包括父节点和父节点下所有子节点变化

  1. /**
  2. * 演示 TreeCache:监听某个节点自己和所有子节点们
  3. */
  4. @Test
  5. public void testTreeCache() throws Exception {
  6. //1. 创建监听器
  7. TreeCache treeCache = new TreeCache(client, "/app2");
  8. //2. 注册监听
  9. treeCache.getListenable().addListener(new TreeCacheListener() {
  10. @Override
  11. public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
  12. System.out.println("节点变化了");
  13. System.out.println(event);
  14. }
  15. });
  16. //3. 开启
  17. treeCache.start();
  18. while (true) {
  19. }
  20. }