https://blog.csdn.net/qq_39063526/article/details/105998288 中的代码
import java.lang.String;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
public class ZookeeperTest {
private ZooKeeper zooKeeper;
private static final String SERVER="hadoop1002:2181,hadoop1003:2181,hadoop1004:2181";
private static final int SS_TIMEOUT=2000;
@Before
public void before() throws IOException {
zooKeeper=new ZooKeeper(SERVER, SS_TIMEOUT, new Watcher() {
//这是一个回调方法! 可以自定义
public void process(WatchedEvent watchedEvent) {
System.out.println("默认监听器");
}
});
}
@Test
public void ls () throws KeeperException, InterruptedException {
List<String> children = zooKeeper.getChildren("/", true);
System.out.println("=========================");
for(String s:children)
{
System.out.println(s);
}
System.out.println("=========================");
}
@Test
public void create() throws KeeperException, InterruptedException {
String s = zooKeeper.create("/IDEA", "stw".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
System.out.println(s);
Thread.sleep(Long.MAX_VALUE);//因为创建的是临时结点,如果直接跳出结点会消失
}
@Test
public void get() throws KeeperException, InterruptedException {
Stat exists = zooKeeper.exists("/aaa", false);
if (exists != null) {
byte[] data = zooKeeper.getData("/aaa", false, exists);
System.out.println(data.toString());
System.out.println(new String(data));
}
else
System.out.println("文件不存在");
}
@Test
public void set() throws KeeperException, InterruptedException {
Stat exists = zooKeeper.exists("/aaa", false);
if (exists != null) {
zooKeeper.setData("/aaa", "stw.dadasdasd".getBytes(),exists.getVersion());
System.out.println(exists.getDataLength());
}
}
@Test
public void delete() throws KeeperException, InterruptedException {
Stat exists = zooKeeper.exists("/aaa", false);
if(exists!=null)
zooKeeper.delete("/aaa",exists.getVersion());
else
System.out.println("要删除的结点不存在");
}
public void rmr() throws KeeperException, InterruptedException {
//rmr
ZKUtil.deleteRecursive(zooKeeper,"/aaa");
}
public void register() throws KeeperException, InterruptedException {
byte[] data = zooKeeper.getData("/aaa", new Watcher() {
public void process(WatchedEvent watchedEvent) {
try {
register();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, null);
System.out.println(new String(data));
}
@Test
public void testReg() {
try {
register();
Thread.sleep(Long.MAX_VALUE);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}