package zookeeper_java;
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.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
public class SimpleZkClient {
//写三个,一个连不上还可以连其它的
private static final String connectString ="node1:2181,node2:2181,node3:2181";
private static final int sessionTimeout=2000; //设置超时时间为2秒
ZooKeeper zkClient=null;
@Before
public void init() throws Exception {
zkClient=new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent event) {
// 收到事件通知后的回调函数,事件处理逻辑
//事件类型和事件路径(节点)
System.out.println(event.getType()+"-------"+event.getPath());
//可实现反复监听
try {
zkClient.getChildren("/", true);
} catch (Exception e) {
e.printStackTrace();
}
}
} );
}
/**
* 数据的增删改查
* @throws Exception
* @throws KeeperException
*/
//创建数据节点到zk中
public void testCreate() throws Exception {
//1.路径 2.写入的data 3.权限,开放给所有人 4.节点类别,持久的
String nodeCreated= zkClient.create("/eclipse", "hello zookeeper".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//上传的数据可以是任何数据,但都要转成byte[]数组
}
//判断节点是否存在
public void testExist() throws Exception{
//节点下的数据就封装在stat中
Stat stat = zkClient.exists("/eclipse", false);
System.out.println(stat==null?"not exist":"exist");
}
//获取子节点
public void getChildren() throws Exception {
//getChildren相当于linux中的ls /,所以监听的是节点的变化
List<String> children = zkClient.getChildren("/", true);
for (String child : children) {
System.out.println(child);
}
}
//获取node数据
public void getData() throws Exception {
byte[] data = zkClient.getData("/eclipse", null, null);
System.out.println(new String(data));
}
//删除node数据
public void delData() throws Exception {
//-1表示删除所有版本的数据
zkClient.delete("/eclipse", -1);
}
//更改node数据
@Test
public void setData() throws Exception {
zkClient.setData("/app1", "i miss you !!!".getBytes(), -1);
byte[] data = zkClient.getData("/app1", null, null);
System.out.println(new String(data));
}
}