zookeeper-编程

使用cli操作zookeeper

//创建节点
create /test "hello"
create /test/dr1 null
create -s /test/index null //创建顺序节点
create -s -e /test/index null //创建顺序临时节点
//获取节点,设置监听
get /test/dr watch //对/test/dr进行监听,只监听一次
//设置数据
set /test/dr 111
//监听节点中子节点的变化
ls2 /test watch 
ls  /test //列出子节点
delete /test //删除单个节点,前提是节点中么有子节点
rmr /test //删除节点,及其下面的子节点

java操作zookeeper

  • 创建连接
public ZooKeeper connect(String host) throws IOException,InterruptedException {

        zoo = new ZooKeeper(host,5000,new Watcher() {
        //连接成功后回调
            public void process(WatchedEvent we) {
                if (we.getState() == Event.KeeperState.SyncConnected) {
                    connectedSignal.countDown();
                }
            }
        });

        connectedSignal.await();
        return zoo;
    }
  • 对zookeeper上的节点进行操作
//创建节点,在创建时需要指定节点的安全权限,节点类型(是否为临时节点、是否为顺序节点)。返回的为节点名称(可能和创建的节点名称不同,例如顺序节点)
String createStr=zooKeeper.create("/test/java1","hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

//在节点上设置监听
zooKeeper.getData(PATH, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    System.out.println(watchedEvent.getType());
                    try {
                        System.out.println(new String(finalZooKeeper.getData(PATH,false,null)));
                    } catch (KeeperException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },null);

    //修改数据前需要先判断节点是否存在,同时获取到节点上的版本号(可以从stat中获取)
    Stat stat=zooKeeper.exists(PATH,false);
    System.out.println(stat.getVersion());
    zooKeeper.setData(PATH,"hello zk".getBytes(),stat.getVersion());

    //获取所有的子节点
    List<String> childrenList=zooKeeper.getChildren("/test",false);

    //删除节点,删除时也需要获取到版本号
    zooKeeper.delete("/test/dr",stat.getVersion());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值