完整代码
package yan.dong.text;
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 TestZK {
private String connectString = "192.168.184.128:2181,192.168.184.129:2181,192.168.184.130:2181";
private ZooKeeper zookeeper;
private int sessionTimeout = 60 * 1000;
@Before
public void init() throws IOException {
zookeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
System.out.println("业务处理代码");
System.out.println(watchedEvent.getType());
}
});
}
@Test
public void createNode() throws InterruptedException, KeeperException {
String str = zookeeper.create("/France", "bali".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("该节点已经创建");
}
@Test
public void getNodeData() throws InterruptedException, KeeperException {
byte[] data = zookeeper.getData("/japan", false, new Stat());
String information = new String(data);
System.out.println("查询到的数据为" + information);
}
@Test
public void updateData() throws InterruptedException, KeeperException {
Stat stat = zookeeper.setData("/France", "lufugong".getBytes(), 0);
System.out.println(stat);
}
@Test
public void delete() throws InterruptedException, KeeperException {
zookeeper.delete("/France", 1);
System.out.println("删除成功");
}
@Test
public void getChildren() throws InterruptedException, KeeperException {
List<String> list = zookeeper.getChildren("/meituan", false);
for (String children : list) {
System.out.println(children);
}
}
@Test
public void watchNode() throws InterruptedException, KeeperException, IOException {
List<String> list = zookeeper.getChildren("/", true);
for (String children : list) {
System.out.println(children);
}
System.in.read();
}
@Test
public void exist() throws InterruptedException, KeeperException {
Stat stat = zookeeper.exists("/dog", false);
System.out.println(stat == null ? "不存在" : "存在");
}
}
|