使用 zookeeper原生的 API
1. 导入pom依赖
<!-- junit 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
<!-- log4j -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
</dependency>
<!-- zookeeper -->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.5.7</version>
</dependency>
<!--json对象格式化工具-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
2. 主要 API
ZkClient.java
package com.hejjon.zk;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hejjon.zk.bean.MyConfig;
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;
/**
* zookeeper 客户端
* Created by caoshi at 11:10 2022-07-03
*/
public class ZkClient {
private static final String ZK_CONNECSTING = "42.192.150.81:2181";
private static final int SESSION_TIMEOUT = 20000;
private ZooKeeper zkClient;
@Before
public void init() throws IOException {
zkClient = new ZooKeeper(ZK_CONNECSTING, SESSION_TIMEOUT, new Watcher() {
public void process(WatchedEvent watchedEvent) {
System.out.println("--------------------------------------------");
List<String> children = null;
try {
children = zkClient.getChildren("/", true);
if (children != null) {
for (String child : children) {
System.out.println(child);
}
}
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
System.out.println("--------------------------------------------");
}
});
}
/**
* 创建节点
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void create() throws KeeperException, InterruptedException {
String node = zkClient.create("/weicx", "testdata".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
/**
* 获取节点及子节点
* @throws KeeperException
* @throws InterruptedException
*/
@Test
public void getChildren() throws KeeperException, InterruptedException {
List<String> children = zkClient.getChildren("/", true);
for (String child : children) {
System.out.println(child);
}
Thread.sleep(Long.MAX_VALUE);
}
/**
* 指定节点设置值
* @throws KeeperException
* @throws InterruptedException
* @throws JsonProcessingException
*/
@Test
public void setData() throws KeeperException, InterruptedException, JsonProcessingException {
Stat stat = null;
ObjectMapper objectMapper = new ObjectMapper();
MyConfig myConfig = new MyConfig();
myConfig.setKey("aaaaa");
myConfig.setName("bbbbb");
byte[] bytes = objectMapper.writeValueAsBytes(myConfig);
stat = zkClient.setData("/myconfig", bytes, -1);
System.out.println(">>>>>>>>>>>>>>>> stat version: " + stat.getVersion());
}
}
3. 监听节点数据变化
ZkClient2.java
package com.hejjon.zk;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hejjon.zk.bean.MyConfig;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* Created by caoshi at 11:47 2022-07-03
*/
public class ZkClient2 {
private static Logger logger = LoggerFactory.getLogger(ZkClient2.class);
private static final String ZK_CONNECSTING = "42.192.150.81:2181";
private static final int SESSION_TIMEOUT = 20000;
private ZooKeeper zkClient;
@Before
public void testWatchData() throws IOException, KeeperException, InterruptedException {
ObjectMapper objectMapper = new ObjectMapper();
zkClient = new ZooKeeper(ZK_CONNECSTING, SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (event.getType() == Event.EventType.NodeDataChanged
&& event.getPath() != null && event.getPath().equals("/myconfig")) {
logger.info("节点 {} 数据发生了变化", event.getPath());
// 获取数据,并使用this再次设置此监听器,实现重复监听节点值的修改
try {
byte[] data = zkClient.getData("/myconfig", this, null);
MyConfig newConfig = objectMapper.readValue(data, MyConfig.class);
logger.info("节点数据变化:{}", newConfig);
} catch (KeeperException | InterruptedException | IOException e) {
e.printStackTrace();
}
}
}
});
// 创建数据对象,并将其转成byte 数组格式
MyConfig myConfig = new MyConfig();
myConfig.setKey("anykey");
myConfig.setName("anyName");
byte[] bytes = objectMapper.writeValueAsBytes(myConfig);
// 判断 /myconfig 节点是否存在,若存在则先删除节点
Stat exists = zkClient.exists("/myconfig", true);
if (exists != null) {
logger.info("节点 /myconfig 已存在");
zkClient.delete("/myconfig", -1);
}
String s = zkClient.create("/myconfig", bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
@Test
public void getData() throws InterruptedException, KeeperException {
byte[] data = zkClient.getData("/myconfig", true, null);
String str = new String(data);
System.out.println(">>>>>>>>>>>>> 获取到/myconfig 节点的值: " + str);
Thread.sleep(Long.MAX_VALUE); // 起到延时作用
}
}
监听节点数据变化操作:
1. 首先运行 ZkClient2.java 的getData 方法,首先获取到的是/myconfig 节点原始的值。注意getData方法中加入了延时,所以程序会一直阻塞着,等待节点数据被修改。
2. 再运行 ZkClient.java 中的 setData 方法,此方法给节点 /myconfig 重新设置值。
3. 观察ZkClient2.java 的控制台打印信息,每次运行 setData方法控制台都会打印节点数据被修改的信息。
监听原理:
注意看监听节点数据变化的那一部分代码。由于这个监听是一次性的,即一次设置监听只可以监听到一次节点数据的变化,再次修改节点数据是监听不到的。所以写成
byte[] data = zkClient.getData("/myconfig", this, null);
将之前设置的监听器 this对象重新设置进去,这样就实现了重复的监听!
Junit 单元测试补充说明:
注意到 junit的 @Before 注解的作用,加上此注解,可以使运行 junit测试类的任何方法之前都会执行一次 @Before 注解标记的方法。