zookeeper学习02-Java API操作
Posted Weikun Xing
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了zookeeper学习02-Java API操作相关的知识,希望对你有一定的参考价值。
文章目录
群启群停脚本
三台虚拟机一台一台启动和查看状态十分麻烦,所以用一个群启群停脚本来操作,大家可以根据自己具体情况进行修改使用
hadoop102,103,104是我三台虚拟机的主机名,且都进行了ssh免密配置
#!/bin/bash
case $1 in
"start")
for i in hadoop102 hadoop103 hadoop104
do
echo ---------- zookeeper $i 启动 ------------
ssh $i "/opt/software/zookeeper-3.5.7/bin/zkServer.sh start"
done
;;
"stop")
for i in hadoop102 hadoop103 hadoop104
do
echo ---------- zookeeper $i 停止 ------------
ssh $i "/opt/software/zookeeper-3.5.7/bin/zkServer.sh stop"
done
;;
"status")
for i in hadoop102 hadoop103 hadoop104
do
echo ---------- zookeeper $i 状态 ------------
ssh $i "/opt/software/zookeeper-3.5.7/bin/zkServer.sh status"
done
;;
esac
启动zookeeper后查看节点状态,成功后进行下一步操作
IDEA环境搭建
1)创建一个Maven Module
2)添加pom文件
pom.xml文件如下,仅作参考
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Zookeeper</artifactId>
<version>1.0-SNAPSHOT</version>
<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>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.7</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>
需要在项目的src/main/resources目录下,新建一个文件,命名为“log4j.properties”,在文件中填入。
log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
TestZkClient类文件内容如下,有点多,下面会逐步解释
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
/**
* ZK的Java客户端
* 1. 获取和ZK的连接对象
* 2. 操作各种API
* 3. 关闭资源
*/
public class TestZkClient
private ZooKeeper zk;
/**
*
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void testDeleteAll() throws KeeperException, InterruptedException
testDeleteNodes("/sanguo", zk);
/**
* 递归删除非空节点
* @param path
* @param zk
* @throws KeeperException
* @throws InterruptedException
*/
public void testDeleteNodes(String path, ZooKeeper zk) throws KeeperException, InterruptedException
Stat stat = zk.exists(path, false);
if(stat != null)
System.out.println("/sanguo 存在");
// 先获取子节点
List<String> children = zk.getChildren(path, false);
if(children != null)
// 递归删除
for (String child : children)
// 先删除子节点
testDeleteNodes(path + "/" + child, zk);
zk.delete(path, -1);
else
// 删除自己
zk.delete(path,-1);
else
System.out.println("/sanguo 不存在");
/**
* 测试删除空节点的值
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void testDelete() throws KeeperException, InterruptedException
String path = "/sanguo";
Stat stat = zk.exists(path, false);
if(stat != null)
System.out.println("/sanguo 存在");
// 删除空节点
zk.delete(path, stat.getVersion());
else
System.out.println("/sanguo 不存在");
@Test
public void testSetData() throws KeeperException, InterruptedException
String path = "/sanguo";
Stat stat = zk.exists("/sanguo", false);
if(stat != null)
System.out.println("/sanguo 存在");
zk.setData(path, "yizhou".getBytes(), stat.getVersion());
else
System.out.println("/sanguo 不存在");
/**
* 获取子节点的数据
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void testGetData() throws KeeperException, InterruptedException
String path = "/sanguo";
Stat stat = zk.exists("/sanguo", false);
if(stat != null)
System.out.println("/sanguo 存在");
byte[] bytes = zk.getData(path, false, stat);
System.out.println(new String(bytes));
else
System.out.println("/sanguo 不存在");
/**
* 判断节点是否存在
*/
@Test
public void testIsExists() throws KeeperException, InterruptedException
Stat stat = zk.exists("/sanguo1", false);
if(stat != null)
System.out.println("/sanguo 存在");
else
System.out.println("/sanguo 不存在");
/**
* 获取子节点
*/
@Test
public void testLsNode() throws KeeperException, InterruptedException
List<String> children = zk.getChildren("/sanguo", new Watcher()
public void process(WatchedEvent event)
System.out.println("监听到/sanguo节点有变化!!!");
);
for (String child : children)
System.out.println(child);
Thread.sleep(Long.MAX_VALUE);
/**
* 创建节点
*/
@Test
public void testCreateNode() throws KeeperException, InterruptedException
String nodePath = zk.create("/sanguo",
"dongwu".getBytes(),
ZooDefs.Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
System.out.println(nodePath);
@Before
public void initZkClient() throws IOException
// 连接ZK集群的地址
String connectionStr = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
// 超时时间
int sessionTimeOut = 10000;
zk = new ZooKeeper(connectionStr, sessionTimeOut, new Watcher()
public void process(WatchedEvent event)
// System.out.println("监听到有变化");
);
@After
public void closeZk() throws InterruptedException
zk.close();
/**
* 获取ZK的连接对象
* @throws IOException
*/
@Test
public void testZkClient() throws IOException
// 连接ZK集群的地址
String connectionStr = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
// 超时时间
int sessionTimeOut = 10000;
ZooKeeper zk = new ZooKeeper(connectionStr, sessionTimeOut, new Watcher()
public void process(WatchedEvent event)
System.out.println("监听到有变化");
);
System.out.println(zk);
初始化ZooKeeper客户端
这步做完还不能运行,代码中有注释,很容易理解
获取子节点列表,不监听
点那个绿色的小对号
获取子节点列表,并监听
点绿色倒三角,运行
在转圈,表示监听中
hadoop102 zookeeper bin目录下./zkCli.sh
监听到子节点发生改变
创建子节点
判断Znode是否存在
换个不存在的节点试一试
获取子节点存储的数据,不监听
获取子节点存储的数据,并监听
监听到节点的值发生变化
设置节点的值
这个没有返回值,不过绿色代表着运行成功
我们来看一下节点的值是否发生了改变
删除空节点
创建空节点/aaa
/aaa已被删除
删除非空节点,递归实现
/sanguo节点已被递归删除
quit退出zkCli
zookeeper Java API操作就是这些了,多敲多练,熟能生巧
关闭虚拟机前一定要关闭zookeeper,养成好习惯,直接关机,下次你启动时可能会报错.
以上是关于zookeeper学习02-Java API操作的主要内容,如果未能解决你的问题,请参考以下文章
zookeeper学习-5Java API操作 - Watcher监听机制
zookeeper学习-4Java API操作 - 服务端和客户端操作
大数据讲课笔记6.6 ZooKeeper的Java API操作