public class ZKTestASync {
public static String connectStr = "192.168.161.128:2181";
public ZooKeeper keeper = null;
private static final Logger log = LoggerFactory.getLogger(ZKTestASync.class);
private static Stat stat = new Stat();
@Before
public void init() {
try {
keeper = new ZooKeeper(connectStr, 3000, (WatchedEvent event) -> {
log.info("事件:{}", event);
if (event.getState() == KeeperState.SyncConnected) {
if (event.getType() == EventType.None && event.getPath() == null) {
} else {
if (event.getType() == EventType.NodeChildrenChanged) {
log.info("节点{}发生变化", event.getPath());
} else if (EventType.NodeDataChanged == event.getType()) {
try {
log.info("节点{}数据发生变化", event.getPath());
this.keeper.getData(event.getPath(), false, stat);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
@After
public void close() {
if (keeper != null)
try {
keeper.close();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testCreateNodeASync() {
this.keeper.create("/node_4", "3".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL, new StringCallback() {
@Override
public void processResult(int rc, String path, Object ctx, String name) {
log.info("rc:{}", rc);
log.info("path:{}", path);
log.info("ctx:{}", ctx);
log.info("name:{}", name);
}
}, "testCreateNodeASync");
}
@Test
public void testGetChildren() {
try {
this.keeper.getChildren("/", true,
(int rc, String path, Object ctx, List<String> children, Stat stat) -> {
log.info("rc:{}", rc);
log.info("path:{}", path);
log.info("ctx:{}", ctx);
log.info("children:{}", children);
log.info("stat:{}", stat);
}, "这里可以传入任何Object作为上下文以便在回调函数函数中使用");
Thread.sleep(3 * 60 * 100);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetData() {
try {
this.keeper.getData("/node_1", true, (int rc, String path, Object ctx, byte[] data, Stat stat) -> {
log.info("rc:{}", rc);
log.info("path:{}", path);
log.info("ctx:{}", ctx);
log.info("data:{}", new String(data));
log.info("stat:{}", stat);
}, null);
Thread.sleep(3 * 60 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testDelete() {
try {
this.keeper.delete("/node_6", -1, (int rc, String path, Object ctx) -> {
log.info("rc:{}", rc);
log.info("path:{}", path);
log.info("ctx:{}", ctx);
}, null);
Thread.sleep(3 * 60 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSetData() {
try {
this.keeper.setData("/node_1", "aaa".getBytes(), -1, (int rc, String path, Object ctx, Stat stat) -> {
log.info("rc:{}", rc);
log.info("path:{}", path);
log.info("ctx:{}", ctx);
log.info("stat:{}", stat);
}, null);
Thread.sleep(3 * 60 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}