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.junit.Before;
import org.junit.Test;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
public class simpleZkClient {
private static final String connectString="mini1:2181,mini2:2181,mini3:2181";
private static final int sessionTimeout = 2000;
ZooKeeper zkClient =null;
@Before
public void init() throws IOException {
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
// TODO Auto-generated method stub
//收到时间通知后的回调函数(应该是我们自己的事件处理逻辑)
System.out.println(event.getType()+"---"+event.getPath());
try {
zkClient.getChildren("/", true); //设置一直监听
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Test
public void test() throws Exception{
Object obj = zkClient.getState();
System.out.println(obj);
}
/**
* 数据的增删改查
*/
//创建数据节点到zk中
public void testCreate() throws KeeperException, InterruptedException {
//参数1:创建节点的路径
//参数2:节点的内容
//参数3:节点权限
//参数4:节点的类型(永久,临时)
String nodeCreated = zkClient.create("/eclipse", "hellozk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//可以是任何数据,但都要专程byte
}
@Test
//判断znode是否存在
public void testExist() throws Exception{
Stat stat = zkClient.exists("/eclipse", true);
//Thread.sleep(Long.MAX_VALUE);
System.out.println(stat==null?"not exist":"exist");
}
@Test
//获取子节点
public void getChildren() throws KeeperException, InterruptedException {
List<String> children = zkClient.getChildren("/", true);
for(String child:children)
{
System.out.println(child);
}
// Thread.sleep(Long.MAX_VALUE);
}
@Test
//获取znode的数据
public void getData() throws KeeperException, InterruptedException {
byte data[] = zkClient.getData("/eclipse", false, new Stat());
System.out.println(new String(data));
}
@Test
//删除节点
public void DeleteZnode() throws Exception {
zkClient.delete("/uu", -1);
}
@Test
//修改节点数据
public void ChangeData() throws Exception{
zkClient.setData("/eclipse", "aaa".getBytes(), -1);
System.out.println(new String(zkClient.getData("/eclipse", false, null)));
}
}