package Zookeeper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.junit.Before;
import org.junit.Test;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
public class ZkDemo {
private static final String connectString = "mini01:2181,mini02:2181,mini03:2181";
private static final int sessionTimeout = 2000;
ZooKeeper zookeeper = null;
@Before
public void init() throws IOException{
zookeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
//收到事件通知后的回调函数
System.out.println(event.getType()+"---"+event.getPath());
}
});
}
/*@Test
创建数据
public void testCreate() throws Exception {
//参数1:要创建的节点的路径
//参数2:要创建节点的数据
//参数3:节点的权限
//参数4:节点的类型
String nodeCreated = zookeeper.create("/app2","helloZK".getBytes(), Ids.OPEN_ACL_UNSAFE权限,CreateMode.PERSISTENT);
} */
//获取子节点
/*@Test
public void getChildren() throws KeeperException, InterruptedException{
List<String> childrens = zookeeper.getChildren("/", true);
for(String children:childrens){
System.out.println(children);
}
}*/
//查询是否存在
/*@Test
public void testExist() throws Exception{
Stat stat = zookeeper.exists("/app100", false);
System.out.println(stat==null?"not exist":"exist");
}*/
//查询数据
@Test
public void getData() throws KeeperException, InterruptedException, Exception{
byte[] data = zookeeper.getData("/app1", false, null);
System.out.println(new String(data,"utf-8"));
}
//删除数据
/*@Test
public void delData() throws Exception, KeeperException{
zookeeper.delete("/app2", -1);
}*/
/* @Test
public void setData() throws Exception{
zookeeper.setData("/app1", "iloveyoucxy".getBytes(), -1);
}
*/
}