一.常用的JAVA API
增删改查与监听 也可用./zkCli.sh打开命令行模式操作
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class SimpleZkClient {
private static final String connectString = "master:2181,slave2: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 watchedEvent) { **//接受处理事件**
System.out.println(watchedEvent.getType()+"---"+watchedEvent.getPath()+"---"+watchedEvent.toString());
try {
getChildren(); //处理完成事件之后本次监听结束 所以需要再次调用
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
public void testCreate() throws KeeperException, InterruptedException { //创建节点 可以传入任意类型的数据,但需要是字节数组形式
String nodeCreated = zooKeeper.create("/testjava", "hellozk".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@Test
public void getChildren() throws KeeperException, InterruptedException { //获取子节点
List<String> children = zooKeeper.getChildren("/",true);
for(String chlid : children){
System.out.println(chlid);
}
}
@Test
public void testNodeExists() throws KeeperException, InterruptedException { //测试节点是否存在
//metadata
Stat stat = zooKeeper.exists("/testjava",false);
System.out.println(stat);
System.out.println(stat==null?"not exists":"exists");
}
@Test
public void getData() throws KeeperException, InterruptedException, UnsupportedEncodingException { //获取节点的数据
byte[] data = zooKeeper.getData("/testjava",false, null);
System.out.println(new String(data,"utf-8"));
//isntance
// Object data = zooKeeper.getData("/testjaav",false, null)
}
}
二.单元测试简介
文中代码的@为单元测试框架junit
可以进行代码块部分的测试而不用取创建main函数
1.@Test: 测试方法
2.@Ignore: 被忽略的测试方法:加上之后,暂时不运行此段代码
3.@Before: 每一个测试方法之前运行
4.@After: 每一个测试方法之后运行
5.@BeforeClass: 方法必须必须要是静态方法(static 声明),所有测试开始之前运行,注意区分before,是所有测试方法
6.@AfterClass: 方法必须要是静态方法(static 声明),所有测试结束之后运行,注意区分 @After
三.程序运行流程简介