博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
zookeeper-JAVA-API操作基础
阅读量:3966 次
发布时间:2019-05-24

本文共 5944 字,大约阅读时间需要 19 分钟。

借鉴于:

创建maven工程并修改相应的pom.xml文件,添加相应的依赖。

junit
junit
RELEASE
org.apache.logging.log4j
log4j-core
2.8.2
org.apache.zookeeper
zookeeper
3.4.10

在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

常用的API操作实例:

package com.buwenbuhuo.zookeeper;import org.apache.zookeeper.KeeperException;import org.apache.zookeeper.WatchedEvent;import org.apache.zookeeper.Watcher;import org.apache.zookeeper.ZooKeeper;import org.junit.Before;import org.junit.Test;import java.io.IOException;import java.util.List;/** * @author 卜温不火 * @create 2020-04-27 22:01 * com.buwenbuhuo.zookeeper - the name of the target package where the new class or interface will be created. * ZooKeeper0427 - the name of the current project. */public class ZkClient {
private ZooKeeper zkCli; private static final String CONNECT_STRING = "hadoop002:2181,hadoop003:2181,hadoop004:2181"; private static final int SESSION_TIMEOUT = 2000;// @Before// public void before() throws IOException {
// zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, new Watcher() {
// public void process(WatchedEvent watchedEvent) {
//// }// });// } // 此部分为上部分的简写 @Before public void before() throws IOException {
zkCli = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, e -> {
System.out.println("默认回调函数"); }); } @Test public void ls() throws KeeperException,InterruptedException{
List
children = zkCli.getChildren("/",true); System.out.println("==========================================="); for (String child: children){
System.out.println(child); } System.out.println("==========================================="); Thread.sleep(Long.MAX_VALUE); }}

**创建zookeeper客户端的操作:**注意连接使用的是当初配置zoo.cfg文件时的2181端口

private static String connectString = "hadoop002:2181,hadoop003:2181,hadoop004:2181";	private static int sessionTimeout = 2000;	private ZooKeeper zkClient = null;	@Before	public void init() throws Exception {
zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
@Override public void process(WatchedEvent event) {
// 收到事件通知后的回调函数(用户的业务逻辑) System.out.println(event.getType() + "--" + event.getPath()); // 再次启动监听 try {
zkClient.getChildren("/", true); } catch (Exception e) {
e.printStackTrace(); } } }); }

创建子节点:

// 创建子节点@Testpublic void create() throws Exception {
// 参数1:要创建的节点的路径; 参数2:节点数据 ; 参数3:节点权限 ;参数4:节点的类型 String nodeCreated = zkClient.create("/sanguo", "jinlian".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);}

获取子节点并监听节点变化:

// 获取子节点@Testpublic void getChildren() throws Exception {
List
children = zkClient.getChildren("/", true); for (String child : children) {
System.out.println(child); } // 延时阻塞 Thread.sleep(Long.MAX_VALUE);}

判断znode是否存在:

// 判断znode是否存在@Testpublic void exist() throws Exception {
Stat stat = zkClient.exists("/IDEA", false); System.out.println(stat == null ? "not exist" : "exist");}

基础操作:

public static void main(String[] args) throws Exception {
// 初始化 ZooKeeper实例(zk地址、会话超时时间,与系统默认一致、watcher) ZooKeeper zk = new ZooKeeper("hadoop002:2181,hadoop003,hadoop004", 30000, new Watcher() {
@Override public void process(WatchedEvent event) {
System.out.println("事件类型为:" + event.getType()); System.out.println("事件发生的路径:" + event.getPath()); System.out.println("通知状态为:" +event.getState()); } }); zk.create("/myGirls", "性感的".getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); zk.close();

常用操作:

public static void main(String[] args) throws Exception {
// 初始化 ZooKeeper实例(zk地址、会话超时时间,与系统默认一致、watcher) ZooKeeper zk = new ZooKeeper("hadoop002:2181,hadoop003,hadoop004", 30000, new Watcher() {
@Override public void process(WatchedEvent event) {
System.out.println("事件类型为:" + event.getType()); System.out.println("事件发生的路径:" + event.getPath()); System.out.println("通知状态为:" +event.getState()); } }); // 创建一个目录节点 zk.create("/testRootPath", "testRootData".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); // 创建一个子目录节点 zk.create("/testRootPath/testChildPathOne", "testChildDataOne".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); System.out.println(new String(zk.getData("/testRootPath",false,null))); // 取出子目录节点列表 System.out.println(zk.getChildren("/testRootPath",true)); // 修改子目录节点数据 zk.setData("/testRootPath/testChildPathOne","modifyChildDataOne".getBytes(),-1); System.out.println("目录节点状态:["+zk.exists("/testRootPath",true)+"]"); // 创建另外一个子目录节点 zk.create("/testRootPath/testChildPathTwo", "testChildDataTwo".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT); System.out.println(new String(zk.getData("/testRootPath/testChildPathTwo",true,null))); // 删除子目录节点 zk.delete("/testRootPath/testChildPathTwo",-1); zk.delete("/testRootPath/testChildPathOne",-1); // 删除父目录节点 zk.delete("/testRootPath",-1); zk.close();}

如图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xnd7P1DX-1603113534233)(https://s1.ax1x.com/2020/10/08/0wg2sP.png)]

转载地址:http://kicki.baihongyu.com/

你可能感兴趣的文章
Perl 简介
查看>>
Perl 注释
查看>>
数据类型之标量
查看>>
调试 Perl 脚本
查看>>
增强的for循环语句
查看>>
静态导入
查看>>
java 泛型
查看>>
控制结构
查看>>
标准输入输出
查看>>
运算符
查看>>
数据类型之列表与数组
查看>>
比较字符串
查看>>
Java EE 精萃
查看>>
Open Source 精萃
查看>>
Java EE 简介
查看>>
Weblogic 简介
查看>>
观察者模式 (Observer)
查看>>
Java 集合框架
查看>>
Weblogic 精萃
查看>>
Servlet 精萃
查看>>