java操作zookeeper实例代码
本篇内容主要讲解“java操作zookeeper实例代码”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java操作zookeeper实例代码”吧!
成都创新互联主要从事做网站、网站设计、网页设计、企业做网站、公司建网站等业务。立足成都服务云阳,10多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:028-86922220
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
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实例代码”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
文章标题:java操作zookeeper实例代码
文章URL:http://hbruida.cn/article/gjchdh.html