初步认识zookeeper(5)--Apache Curator操作节点(增删改查)

目录概要

  • 初始化连接
  • 增加节点
  • 查询节点
  • 修改节点
  • 删除节点

一、简介
Apache Curator是一个比较完善的ZooKeeper客户端框架,通过封装的一套高级API 简化了ZooKeeper的操作。通过查看官方文档,可以发现Curator主要解决了三类问题:

  • 封装ZooKeeper client与ZooKeeper server之间的连接处理
  • 提供了一套Fluent风格的操作API
  • 提供ZooKeeper各种应用场景(recipe, 比如:分布式锁服务、集群领导选举、共享计数器、缓存机制、分布式队列等)的抽象封装

二、在pom.xml中添加如下依赖

 <dependency>
      <groupId>org.apache.zookeeper</groupId>
      <artifactId>zookeeper</artifactId>
      <version>3.4.10</version>
    </dependency>
    <dependency>
      <groupId>org.apache.curator</groupId>
      <artifactId>curator-framework</artifactId>
      <version>4.2.0</version>
    </dependency>
    <dependency>
      <groupId>org.apache.curator</groupId>
      <artifactId>curator-recipes</artifactId>
      <version>4.2.0</version>
    </dependency>

三、实操

1、初始化连接

CuratorFramework curatorFramework = CuratorFrameworkFactory.builder().
                connectString("192.168.137.128:2181").
                sessionTimeoutMs(4000).retryPolicy(
                        new ExponentialBackoffRetry(1000,3)).
                build();
        curatorFramework.start();

2、添加节点

            //创建
            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).
                    forPath("/www", "xxx".getBytes());

3、查询节点

            //查询
            Stat stat = new Stat();
            byte[] bytes = curatorFramework.getData().storingStatIn(stat).forPath("/www");
            System.out.println("chauxn  "+new String(bytes));

4、修改节点

            //修改
            stat = curatorFramework.setData().withVersion(stat.getVersion()).forPath("/www", "gg".getBytes());

5、删除节点

            //删除
            curatorFramework.delete().deletingChildrenIfNeeded().forPath("/www");

6、关闭连接

curatorFramework.close();
发布了20 篇原创文章 · 获赞 32 · 访问量 5598

猜你喜欢

转载自blog.csdn.net/shuai8624/article/details/96777670