使用curator框架操作zookeeper

1、添加依赖

<dependencies>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.0.1</version>
        </dependency>
    </dependencies>

2、操作zookeeper节点

package com.cn.willy.com.cn.curator.willy;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.Stat;

public class ZookeeperFactory {

public static void main(String[] args) {
    //建立zookeeper连接
    CuratorFramework factory = CuratorFrameworkFactory.builder()
            .connectString("192.168.43.135:2181")
            .connectionTimeoutMs(5000)
            .retryPolicy(new RetryOneTime(300))
            .namespace("fsm")
            .build();

    //打开连接
    factory.start();

    try{
        //节点存在性查询
        System.out.println("check node exists");
        Stat stat = factory.checkExists()
                .forPath("/node");

        if(stat == null){
            //创建节点
            System.out.println("create node");
            factory.create()
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                    .forPath("/node","this is curator".getBytes());
        }
        //获取节点数据
        System.out.println("get node");
        byte[] bytes = factory.getData().forPath("/node");
        System.out.println(new String(bytes));

        //设置节点数据
        System.out.println("update node");
        factory.setData().forPath("/node","set node".getBytes());

        byte[] bytes1 = factory.getData().forPath("/node");
        System.out.println(new String(bytes1));

        //删除节点数据
        System.out.println("delete node");
        Void aVoid = factory.delete()
                .deletingChildrenIfNeeded()
                .forPath("/node");
    }catch (Exception e){
        e.printStackTrace();
    }

    //关闭连接
    System.out.println("start");
    factory.close();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值