1.创建一个Maven工程
2.添加pom文件
代码语言:javascript复制 <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>
创建ZooKeeper客户端
代码语言:javascript复制public class zookeeper {
public final static String connetString="192.168.231.136:2181";
private static int sessionTimeout = 2000;
public static ZooKeeper getZookeeper() throws Exception {
// 创建ZooKeeper客户端
ZooKeeper zooKeeper = new ZooKeeper(connetString, sessionTimeout, new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
}
});
return zooKeeper;
}
}
创建子节点
代码语言:javascript复制 @Test
public void test01() throws Exception {
// 参数1:要创建的节点的路径;
// 参数2:节点数据 ;
// 参数3:节点权限 ;
// 参数4:节点的类型
ZooKeeper zookeeper = com.atguigu.zookeeper.getZookeeper();
String s = zookeeper.create("/777888", "8888".getBytes(StandardCharsets.UTF_8),
ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println(s);
}
获取子节点
代码语言:javascript复制 @Test
public void getChild() throws Exception {
ZooKeeper zookeeper = com.atguigu.zookeeper.getZookeeper();
List<String> children = zookeeper.getChildren("/", true);
for(String child:children)
{
System.out.println(child);
}
}
判断Znode是否存在
代码语言:javascript复制@Test
public void exitTest() throws Exception {
ZooKeeper zookeeper = com.atguigu.zookeeper.getZookeeper();
Stat stat = zookeeper.exists("/idea", false);
System.out.println(stat);
System.out.println(stat == null ? "not exist" : "exist");
}