1)创建一个工程:Zookeeper
2)添加pom文件(Zookeeper,log4j)
log4j log4j1.2.12 org.apache.zookeeper zookeeper3.7.0
3)log4j.properties文件文件放在项目的根目录下
4)创建包和类
private String connectString="172.29.97.56:2181,172.29.97.56:2182,172.29.97.56:2183";
int sessionTimeout =1000;
public ZooKeeper ckClient;
@BeforeEach
public void init() throws IOException, KeeperException, InterruptedException {
ckClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
List children = null;
try {
children = ckClient.getChildren("/china",true);
for (String child:children) {
System.out.println(child);
}
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
//ConNECTED
Thread.sleep(1000);
System.out.println(ckClient.getState());
}
@Test
public void create() throws KeeperException, InterruptedException {
String nodeCreated=ckClient.create("/china/beijing","beijing".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@Test
public void getChildren() throws KeeperException, InterruptedException {
List children = ckClient.getChildren("/china",true);
for (String child:children) {
System.out.println(child);
}
//延迟
Thread.sleep(Long.MAX_VALUE);
}
注意点:1.在其它案例执行前执行,使用junit5的@BeforeEach注解,junit4的是@Before注解,使用不对的话,会导致注解失效。



