Zookeeper的API
1,输出子节点
首先我们从客户端命令行中看到有以下子节点:
则使用API操作:
package zyl;
import java.io.IOException;
import java.util.List;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Before;
import org.junit.Test;
public class ZKCliet {
private ZooKeeper zkCli;
private static final String CONNECT_STRING = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
private static final int SESSTION_TIMEOUT = 2000;
@Before
public void before() throws IOException {
zkCli = new ZooKeeper(CONNECT_STRING, SESSTION_TIMEOUT, new Watcher() {
public void process(WatchedEvent arg0) {
// TODO Auto-generated method stub
System.out.println("默认回调函数");
}
});
}
@Test
public void ls() throws KeeperException, InterruptedException {
List<String> children = zkCli.getChildren("/", true);
System.out.println("=================输出");
for (String chiString : children) {
System.out.println(chiString);
}
System.out.println("=================结束");
}
}
运行结果:
2,创建节点
// 创建子节点
@Test
public void create() throws Exception {
// 参数1:要创建的节点的路径; 参数2:节点数据 ; 参数3:节点权限 ;参数4:节点的类型
String nodeCreated = zkCli.create("/yulong", "BIT".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
客户端命令行中可以看到创建成功:
3,判断节点是否存在:
// 判断znode是否存在
@Test
public void exist() throws Exception {
Stat stat = zkCli.exists("/eclipse", false);
System.out.println(stat == null ? "not exist" : "exist");
}
3,get
@Test
public void get() throws KeeperException, InterruptedException {
byte[] data = zkCli.getData("/yulong", true, new Stat());
String string = new String(data);
System.out.println(string);
}
4,set
@Test
public void set() throws KeeperException, InterruptedException {
Stat stat = zkCli.setData("/yulong", "defabc".getBytes(), 0);
System.out.println(stat.getDataLength());
}
5,stat
@Test
public void stat() throws KeeperException, InterruptedException {
Stat exists = zkCli.exists("/Idea", false);
if (exists == null) {
System.out.println("节点不存在");
} else {
System.out.println(exists.getDataLength());
}
}
6,delete
@Test
public void delete() throws KeeperException, InterruptedException {
Stat exists = zkCli.exists("/zxx0000000007", false);
if (exists != null)
zkCli.delete("/zxx0000000007", exists.getVersion());
}
整个project的pom文件:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.zookeeper/zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.10</version>
</dependency>
</dependencies>