申明一下本系列纯做个人笔记记录用,不会涉及太多原理讲解和算法或者运维知识,且内容浅显,请有需要的自行查阅资料
上回说到客户端shell操作,对节点和信息进行一个维护,这回来看怎么用java代码实现这块。
<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>keeper</groupId><artifactId>zookeeper</artifactId><version>3.4.14</version></dependency>
</dependencies>
2. resource新建log4j.properties 还是直接跑吧
Logger=INFO, stdout, logfile
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/log.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
3.junit代码,均经过测试可运行
package zkmanage;import keeper.*;
import keeper.data.Stat;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.util.List;public class TestZK {private String connectStr = "ubuntu001:2181,ubuntu002:2181,ubuntu003:2181";private int sessionTimeout = 20000;private ZooKeeper zkClient;//初始化client//@Test@Beforepublic void init() throws IOException {zkClient = new ZooKeeper(connectStr, sessionTimeout, new Watcher() {//监听的时候需要编写此处public void process(WatchedEvent watchedEvent) {System.out.println("-------------------监听开始");List<String> children = null;try {children = Children("/", true);} catch (KeeperException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}for (String child: children) {System.out.println(child);}System.out.println("-------------------监听结束");}});}//创建节点@Testpublic void createNode() throws KeeperException, InterruptedException, IOException {String path ate("/leafznode2", "222".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);System.out.println(path);}//获得节点数据@Testpublic void getData() throws KeeperException, InterruptedException {List<String> children = Children("/", false);for (String child: children) {System.out.println(child);}}//获得节点数据并监听节点@Testpublic void getDataAndWatch() throws KeeperException, InterruptedException {List<String> children = Children("/", true);for (String child: children) {System.out.println(child);}Thread.sleep(Long.MAX_VALUE);//启动起来以后去集群上做一些变动,这边程序可以监听到}//判断znode是否存在@Testpublic void exist() throws KeeperException, InterruptedException {Stat stat = ists("/leafznode1", false);System.out.println(stat);System.out.println(stat == null?"not exist":"exist");}
}
本文发布于:2024-01-28 05:40:29,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063916335193.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |