前提:保证hadoop102、hadoop103、hadoop104服务器上Zookeeper集群服务端启动
文章目录客户端的API *** 作
IDEA环境搭建创建ZooKeeper客户端
IDEA环境搭建1.创建一个maven工程
2.添加pom文件
junit junitRELEASE org.apache.logging.log4j log4j-core2.8.2 org.apache.zookeeper zookeeper3.5.7
3.拷贝log4j.properties文件到项目根目录
在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创建ZooKeeper客户端
package com.yingzi.zk; 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; public class zkClient { // //注意:逗号前后不能有空格 private static String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181"; private static int sessionTimeout = 2000; private ZooKeeper zkClient = null; @Before public void init() throws IOException { zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() { @Override public void process(WatchedEvent watchedEvent) { // System.out.println("------------------------------"); // Listchildren = null; // try { // children = zkClient.getChildren("/", true); // // for (String child : children) { // System.out.println(child); // } // // System.out.println("------------------------------"); // } catch (KeeperException e) { // e.printStackTrace(); // } catch (InterruptedException e) { // e.printStackTrace(); // } } }); } //创建子节点 @Test public void create() throws InterruptedException, KeeperException { String nodeCreated = zkClient.create("/yingzi", "ss.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } //获取子节点 @Test public void getChildern() throws InterruptedException, KeeperException { List children = zkClient.getChildren("/", true); for (String child : children) { System.out.println(child); } // 延时阻塞 Thread.sleep(Long.MAX_VALUE); } //判断节点是否存在 @Test public void exist() throws InterruptedException, KeeperException { Stat stat = zkClient.exists("/yingzi", false); System.out.println(stat == null ? "not exist":"exist"); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)