实现了zookeeper上节点的增,删,改,查和监听功能。
1.pom.xml配置:
<!-- 关于Zookeeper客户端的封装,这里只引用的recipes和client -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-recipes</artifactId>
<version>5.1.0</version>
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 关于Zookeeper客户端的封装 -->
<dependency>
<groupId>org.apache.curator</groupId>
<artifactId>curator-client</artifactId>
<version>5.1.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
2.监听节点变动
public static void watchNode() throws Exception {
CuratorFramework client = ZkClient.getClientOne();
client.start();
CountDownLatch countDownLatch = new CountDownLatch(1);
Watcher w = new Watcher() {
@Override
public void process(WatchedEvent watchedEvent) {
EventType eventType = watchedEvent.getType();
String path = watchedEvent.getPath();
System.out.println(eventType+"--- --- ---"+path);
System.out.println("监听到的变化 watchedEvent = " + watchedEvent);
countDownLatch.countDown();
}
};
client.getData().usingWatcher(w).forPath("/demo/curd/node-1");
countDownLatch.await();
client.close();
}
3.两种方式创建客户端
private static final String BROKERS = "10.190.1.38:2181";
public static void main(String[] args) throws Exception {
// ZkClient.createNode();
//ZkClient.asyncCreateNode();
//ZkClient.updateNode();
// ZkClient.readNode();
// ZkClient.deleteNode();
ZkClient.watchNode();
}
private static CuratorFramework getClientOne() {
ExponentialBackoffRetry retry = new ExponentialBackoffRetry(3000, 3);
CuratorFramework client = CuratorFrameworkFactory.newClient(ZkClient.BROKERS, retry);
return client;
}
private static CuratorFramework getClientTwo() {
ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000, 3);
CuratorFramework client = CuratorFrameworkFactory.builder().connectString(ZkClient.BROKERS)
.connectionTimeoutMs(20000).sessionTimeoutMs(20000).retryPolicy(retry).build();
return client;
}
其他内容请参考《https://blog.csdn.net/weixin_43072970/article/details/106848786》。
官方例子下载地址: https://www.apache.org/dyn/closer.lua/curator/5.1.0/apache-curator-5.1.0-source-release.zip 。