Java实现与ZooKeeper的连接(二)
upon the client's disconnect.
*/
this.zooKeeper.create(path, data, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
/**
*
*function:获取节点信息
*@author cuiran
*@createDate 2013-01-16 15:17:22
*@param path
*@throws KeeperException
*@throws InterruptedException
*/
public void getChild(String path) throws KeeperException, InterruptedException{
try{
List list=this.zooKeeper.getChildren(path, false);
if(list.isEmpty()){
log.debug(path+"中没有节点");
}else{
log.debug(path+"中存在节点");
for(String child:list){
log.debug("节点为:"+child);
}
}
}catch (KeeperException.NoNodeException e) {
// TODO: handle exception
throw e;
}
}
public byte[] getData(String path) throws KeeperException, InterruptedException {
return this.zooKeeper.getData(path, false,null);
}
public static void main(String[] args) {
try {
ZooKeeperOperator zkoperator = new ZooKeeperOperator();
zkoperator.connect("192.168.0.138");
byte[] data = new byte[]{'a','b','c','d'};
// zkoperator.create("/root",null);
// System.out.println(Arrays.toString(zkoperator.getData("/root")));
//
// zkoperator.create("/root/child1",data);
// System.out.println(Arrays.toString(zkoperator.getData("/root/child1")));
//
// zkoperator.create("/root/child2",data);
// System.out.println(Arrays.toString(zkoperator.getData("/root/child2")));
String zktest="ZooKeeper的Java API测试";
zkoperator.create("/root/child3", zktest.getBytes());
log.debug("获取设置的信息:"+new String(zkoperator.getData("/root/child3")));
System.out.println("节点孩子信息:");
zkoperator.getChild("/root");
zkoperator.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
最后运行结果:
[plain]
2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.name=Administrator www.2cto.com
2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.home=C:\Documents and Settings\Administrator
2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Client environment:user.dir=D:\workspace\stormdemo1
2013-01-16 15:26:04:INFO org.apache.zookeeper.ZooKeeper - Initiating client connection, connectString=192.168.0.138 sessionTimeout=2000 watcher=com.zoo.demo.ZooKeeperOperator@ca8327
2013-01-16 15:26:04:INFO org.apache.zookeeper.ClientCnxn - Opening socket connection to server /192.168.0.138:2181
2013-01-16 15:26:13:INFO org.apache.zookeeper.ClientCnxn - Socket connection established to 192.168.0.138/192.168.0.138:2181, initiating session
2013-01-16 15:26:13:INFO org.apache.zookeeper.ClientCnxn - Session establishmen