Zookeeper客户端使用

本文介绍了ZooKeeper的Java客户端使用,包括同步与异步创建节点、修改节点数据等操作。同时,也探讨了Curator这一流行的ZooKeeper客户端,展示了如何创建会话、创建节点、获取和更新数据以及删除节点的示例。Curator通过封装常用功能,简化了ZooKeeper的开发工作。
摘要由CSDN通过智能技术生成

一、Java客户端

1.maven依赖

<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.5.8</version>
</dependency>

2.客户端操作

@Slf4j
public class ZookeeperClientTest {

    private static ZooKeeper zooKeeper;

    private static final String ZK_NODE="/zk-node";


    @Before
    public void init() throws IOException, InterruptedException {
        final CountDownLatch countDownLatch=new CountDownLatch(1);
        zooKeeper=new ZooKeeper("127.0.0.1:2181", 5000, event -> {
            if (event.getState()== Watcher.Event.KeeperState.SyncConnected &&
                    event.getType()== Watcher.Event.EventType.None){
                countDownLatch.countDown();
                log.info("连接成功!");
            }
        });
        log.info("连接中....");
        countDownLatch.await();
    }
  
		//同步创建节点
    public void createTest() throws KeeperException, InterruptedException {
        String path = zooKeeper.create(ZK_NODE, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        log.info("created path: {}",path);
		}  
  	//异步创建节点
    public void createAsycTest() throws InterruptedException {
         zooKeeper.create(ZK_NODE, "data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                 CreateMode.PERSISTENT,
                 (rc, path, ctx, name) -> log.info("rc  {},path {},ctx {},name {}",rc,path,ctx,name),"context");
        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
    }  
  	//修改节点数据
    public void setTest() throws KeeperException, InterruptedException {

        Stat stat = new Stat();
        byte[] data = zooKeeper.getData(ZK_NODE, false, stat);
        zooKeeper.setData(ZK_NODE, "changed!".getBytes(), stat.getVersion());
         byte[] dataAfter = zooKeeper.getData(ZK_NODE, false, stat);
    }  
}

二、Curator 开源客户端

Curator 是一套由netflix 公司开源的,Java 语言编程的 ZooKeeper 客户端框架,Curator项目是现在ZooKeeper客户端中使用最多,对ZooKeeper 版本支持最好的第三方客户端。Curator 把平时常用的很多 ZooKeeper 服务开发功能做了封装,减少了在使用 ZooKeeper 时的大部分底层细节开发工作。

1.maven依赖

<dependency>
    <groupId>org.apache.curator</groupId>
    <artifactId>curator-recipes</artifactId>
    <version>5.0.0</version>
    <exclusions>
        <exclusion>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.apache.zookeeper</groupId>
    <artifactId>zookeeper</artifactId>
    <version>3.5.8</version>
</dependency>

2.客户端操作

//创建会话。最核心的类是CuratorFramework,定义一个 ZooKeeper 客户端对象,并在之后的上下文中使用。
//ExponentialBackoffRetry	重试一组次数,重试之间的睡眠时间增加
//RetryNTimes							重试最大次数
//RetryOneTime						只重试一次
//RetryUntilElapsed				在给定的时间结束之前重试
CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, new ExponentialBackoffRetry(1000, 3));
client.start();

//创建节点
//使用 create 函数创建数据节点;
//通过 withMode 函数指定节点类型,默认是持久化节点;
//调用 forPath 函数来指定节点的路径和数据信息。
curatorFramework.create().forPath("/curator-node");
curatorFramework.create().withMode(CreateMode.PERSISTENT).forPath("/curator-node","some-data".getBytes());
curatorFramework.create().creatingParentsIfNeeded().forPath("/node-parent/sub-node-1");//创建带层级结构的节点

//获取数据  getData函数
byte[] bytes = curatorFramework.getData().forPath("/curator-node");

//更新节点  setData函数
curatorFramework.setData().forPath("/curator-node","changed!".getBytes());

//删除节点  delete函数
//guaranteed:起到一个保障删除成功的作用,其底层工作方式是:只要该客户端的会话有效,就会在后台持续发起删除请求,直到该数据节点被删除。
//deletingChildrenIfNeeded:指定了该函数后,系统在删除该数据节点的时候会以递归的方式直接删除其子节点以及子节点的子节点。
curatorFramework.delete().guaranteed().deletingChildrenIfNeeded().forPath(pathWithParent);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值