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();

}

}


}


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/31537584/viewspace-2305584/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/31537584/viewspace-2305584/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值