温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java操作zookeeper实例代码

发布时间:2021-09-16 20:50:15 来源:亿速云 阅读:116 作者:chen 栏目:数据库

本篇内容主要讲解“java操作zookeeper实例代码”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java操作zookeeper实例代码”吧!

package com.rxzx.demo;

import java.io.IOException;

import java.util.List;

import org.apache.zookeeper.CreateMode;

import org.apache.zookeeper.KeeperException;

import org.apache.zookeeper.WatchedEvent;

import org.apache.zookeeper.Watcher;

import org.apache.zookeeper.ZooDefs.Ids;

import org.apache.zookeeper.ZooKeeper;

import org.apache.zookeeper.data.Stat;

public class ZKDemo {

    //连接zookeeper的超时时长(毫秒)

private static final int OUT_TIME=60000;

//zookeeper集群连接对象

private ZooKeeper zk;

//自定义监听事件对象

private Watcher wc=new Watcher(){

@Override

public void process(WatchedEvent event) {

// TODO Auto-generated method stub

if(event.getType()==Event.EventType.NodeDataChanged){

System.out.println(event.getPath()+"    "+event.getType());

}else{

System.out.println(event.getPath()+"    "+event.getType());

}

}

};

//获取监控对象

public Watcher getWatcher(){

return this.wc;

}

//获取zookeeper集群连接对象

public ZooKeeper getZooKeeper(){

if(zk==null){

try {

zk=new ZooKeeper("192.168.2.100:2181,192.168.2.101:2181,192.168.2.102:2181",OUT_TIME,null);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return zk;

}

//关闭zookeeper连接对象

public void close(){

if(zk!=null){

try {

zk.close();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

ZKDemo zd=new ZKDemo();

try {

//获取zookeeper连接对象

ZooKeeper zk=zd.getZooKeeper();

//遍历node节点的子节点

List<String> nodelist=zk.getChildren("/node", zd.getWatcher());

for(String s:nodelist){

System.out.println(s);

}

//创建node的子节点son

//zk.create("/node/son", "hello word".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);

//判断数据节点是否存在,如果存在则返回该对象

Stat son=zk.exists("/node/son0000000011", zd.getWatcher());

if(son!=null){

System.out.println(son.getCzxid());

}else{

System.out.println("该节点不存在");

}

//对数据节点的数据内容进行修改

//zk.setData("/node/son0000000011", "wwwwww".getBytes(), -1);

//Stat stat=new Stat();

//获取数据节点的数据内容

//byte[] d=zk.getData("/node/son0000000011", zd.getWatcher(), null);

//System.out.println(new String(d));

//System.out.println(stat.getCzxid());

zk.delete("/node/son4", -1);

System.out.println("操作完成");

} catch (KeeperException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}finally{

zd.close();

}

}

}

到此,相信大家对“java操作zookeeper实例代码”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI