五、Zookeeper基于API操作Node节点
安装zookeeper :linux下安装Zookeeper 3.4.14
zookeeper 分为5个包:
org.apache.zookeeper //客户端主要类文件
org.apache.zookeeper.data //
org.apache.zookeeper.server
org.apache.zookeeper.server.quorum
org.apache.zookeeper.server.upgrade
建立会话
引入依赖:
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.14</version>
</dependency>
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper; import java.io.IOException;
import java.util.concurrent.CountDownLatch; public class CreateSession implements Watcher { private static CountDownLatch countDownLatch = new CountDownLatch(1); /*
建立会话
*/
public static void main(String[] args) throws IOException, InterruptedException { /*
客户端可以通过创建一个zk实例来连接zk服务器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 连接地址:IP:端口
sesssionTimeOut:会话超时时间:单位毫秒
Wather:监听器(当特定事件触发监听时,zk会通过watcher通知到客户端)
*/ ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSession());
System.out.println(zooKeeper.getState()); // 计数工具类:CountDownLatch:不让main方法结束,让线程处于等待阻塞
countDownLatch.await(); System.out.println("客户端与服务端会话真正建立了"); } /*
回调方法:处理来自服务器端的watcher通知
*/
public void process(WatchedEvent watchedEvent) {
// SyncConnected
if(watchedEvent.getState() == Event.KeeperState.SyncConnected){ //解除主程序在CountDownLatch上的等待阻塞
System.out.println("process方法执行了...");
countDownLatch.countDown(); } }
}
注意:ZooKeeper客户端和服务端会话的建立是一个异步的过程,也就是说在程序中,构造方法会在处理完客户端初始化工作后立即返回,在大多数情况下,此时并没有真正建立好一个可用的会话,在会话的生命周期中处于“ CONNECTING的状态。当该会话真正创建完毕后 ZooKeeper服务端会向会话对应的客户端发送一个事件通知,以告知客户端,客户端只有在获取这个通知之后,才算真正建立了会话
创建节点
节点介绍:
/**
* path :节点创建的路径
* data[] :节点创建要保存的数据,是个byte类型的
* acl :节点创建的权限信息(4种类型)
* ANYONE_ID_UNSAFE : 表示任何人
* AUTH_IDS :此ID仅可用于设置ACL。它将被客户机验证的ID替换。
* OPEN_ACL_UNSAFE :这是一个完全开放的ACL(常用)--> world:anyone
* CREATOR_ALL_ACL :此ACL授予创建者身份验证ID的所有权限
* createMode :创建节点的类型(4种类型)
* PERSISTENT:持久节点
* PERSISTENT_SEQUENTIAL:持久顺序节点
* EPHEMERAL:临时节点
* EPHEMERAL_SEQUENTIAL:临时顺序节点
String node = zookeeper.create(path,data,acl,createMode);
*/
import org.apache.zookeeper.*; import java.io.IOException;
import java.util.concurrent.CountDownLatch; public class CreateNote implements Watcher { private static CountDownLatch countDownLatch = new CountDownLatch(1); private static ZooKeeper zooKeeper; /*
建立会话
*/
public static void main(String[] args) throws IOException, InterruptedException, KeeperException { /*
客户端可以通过创建一个zk实例来连接zk服务器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 连接地址:IP:端口
sesssionTimeOut:会话超时时间:单位毫秒
Wather:监听器(当特定事件触发监听时,zk会通过watcher通知到客户端)
*/ zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateNote());
System.out.println(zooKeeper.getState()); // 计数工具类:CountDownLatch:不让main方法结束,让线程处于等待阻塞
//countDownLatch.await();\
Thread.sleep(Integer.MAX_VALUE); } /*
回调方法:处理来自服务器端的watcher通知
*/
public void process(WatchedEvent watchedEvent) {
// SyncConnected
if(watchedEvent.getState() == Event.KeeperState.SyncConnected){ //解除主程序在CountDownLatch上的等待阻塞
System.out.println("process方法执行了...");
// 创建节点
try {
createNoteSync();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} } } /*
创建节点的方法
*/
private static void createNoteSync() throws KeeperException, InterruptedException { /**
* path :节点创建的路径
* data[] :节点创建要保存的数据,是个byte类型的
* acl :节点创建的权限信息(4种类型)
* ANYONE_ID_UNSAFE : 表示任何人
* AUTH_IDS :此ID仅可用于设置ACL。它将被客户机验证的ID替换。
* OPEN_ACL_UNSAFE :这是一个完全开放的ACL(常用)--> world:anyone
* CREATOR_ALL_ACL :此ACL授予创建者身份验证ID的所有权限
* createMode :创建节点的类型(4种类型)
* PERSISTENT:持久节点
* PERSISTENT_SEQUENTIAL:持久顺序节点
* EPHEMERAL:临时节点
* EPHEMERAL_SEQUENTIAL:临时顺序节点
String node = zookeeper.create(path,data,acl,createMode);
*/ // 持久节点
String note_persistent = zooKeeper.create("/g-persistent", "持久节点内容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); // 临时节点
String note_ephemeral = zooKeeper.create("/g-ephemeral", "临时节点内容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); // 持久顺序节点
String note_persistent_sequential = zooKeeper.create("/g-persistent_sequential", "持久顺序节点内容".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); System.out.println("创建的持久节点" + note_persistent);
System.out.println("创建的临时节点" + note_ephemeral);
System.out.println("创建的持久顺序节点" + note_persistent_sequential); }
}
读取节点:
public class GetNoteData implements Watcher { private static CountDownLatch countDownLatch = new CountDownLatch(1); private static ZooKeeper zooKeeper; /*
建立会话
*/
public static void main(String[] args) throws IOException, InterruptedException, KeeperException { /*
客户端可以通过创建一个zk实例来连接zk服务器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 连接地址:IP:端口
sesssionTimeOut:会话超时时间:单位毫秒
Wather:监听器(当特定事件触发监听时,zk会通过watcher通知到客户端)
*/ zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new GetNoteData());
System.out.println(zooKeeper.getState()); // 计数工具类:CountDownLatch:不让main方法结束,让线程处于等待阻塞
//countDownLatch.await();\
Thread.sleep(Integer.MAX_VALUE); } /*
回调方法:处理来自服务器端的watcher通知
*/
public void process(WatchedEvent watchedEvent) { /*
子节点列表发生改变时,服务器端会发生noteChildrenChanged事件通知
要重新获取子节点列表,同时注意:通知是一次性的,需要反复注册监听
*/
if(watchedEvent.getType() == Event.EventType.NodeChildrenChanged){ List<String> children = null;
try {
children = zooKeeper.getChildren("/g-persistent", true);
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(children); } // SyncConnected
if(watchedEvent.getState() == Event.KeeperState.SyncConnected){ //解除主程序在CountDownLatch上的等待阻塞
System.out.println("process方法执行了..."); // 获取节点数据的方法
try {
getNoteData(); // 获取节点的子节点列表方法
getChildrens();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} } } /*
获取某个节点的内容
*/
private void getNoteData() throws KeeperException, InterruptedException { /**
* path : 获取数据的路径
* watch : 是否开启监听
* stat : 节点状态信息
* null: 表示获取最新版本的数据
* zk.getData(path, watch, stat);
*/
byte[] data = zooKeeper.getData("/g-persistent", false, null);
System.out.println(new String(data)); } /*
获取某个节点的子节点列表方法
*/
public static void getChildrens() throws KeeperException, InterruptedException { /*
path:路径
watch:是否要启动监听,当子节点列表发生变化,会触发监听
zooKeeper.getChildren(path, watch);
*/
List<String> children = zooKeeper.getChildren("/g-persistent", true);
System.out.println(children); } }
删除节点
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat; import java.io.IOException;
import java.util.concurrent.CountDownLatch; public class DeleteNote implements Watcher { private static CountDownLatch countDownLatch = new CountDownLatch(1); private static ZooKeeper zooKeeper; /*
建立会话
*/
public static void main(String[] args) throws IOException, InterruptedException, KeeperException { /*
客户端可以通过创建一个zk实例来连接zk服务器
new Zookeeper(connectString,sesssionTimeOut,Wather)
connectString: 连接地址:IP:端口
sesssionTimeOut:会话超时时间:单位毫秒
Wather:监听器(当特定事件触发监听时,zk会通过watcher通知到客户端)
*/ zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new DeleteNote());
System.out.println(zooKeeper.getState()); // 计数工具类:CountDownLatch:不让main方法结束,让线程处于等待阻塞
//countDownLatch.await();\
Thread.sleep(Integer.MAX_VALUE); } /*
回调方法:处理来自服务器端的watcher通知
*/
public void process(WatchedEvent watchedEvent) {
// SyncConnected
if(watchedEvent.getState() == Event.KeeperState.SyncConnected){ //解除主程序在CountDownLatch上的等待阻塞
System.out.println("process方法执行了...");
// 删除节点
try {
deleteNoteSync();
} catch (KeeperException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} } } /*
删除节点的方法
*/
private void deleteNoteSync() throws KeeperException, InterruptedException { /*
zooKeeper.exists(path,watch) :判断节点是否存在
zookeeper.delete(path,version) : 删除节点
*/ Stat stat = zooKeeper.exists("/g-persistent/c1", false);
System.out.println(stat == null ? "该节点不存在":"该节点存在"); if(stat != null){
zooKeeper.delete("/g-persistent/c1",-1);
} Stat stat2 = zooKeeper.exists("/g-persistent/c1", false);
System.out.println(stat2 == null ? "该节点不存在":"该节点存在"); } }
更新节点
/*
更新数据节点内容的方法
*/
private void updateNoteSync() throws KeeperException, InterruptedException { /*
path:路径
data:要修改的内容 byte[]
version:为-1,表示对最新版本的数据进行修改
zooKeeper.setData(path, data,version);
*/ byte[] data = zooKeeper.getData("/g-persistent", false, null);
System.out.println("修改前的值:" + new String(data)); //修改/lg-persistent 的数据 stat: 状态信息对象
Stat stat = zooKeeper.setData("/g-persistent", "客户端修改了节点数据".getBytes(), -1); byte[] data2 = zooKeeper.getData("/g-persistent", false, null);
System.out.println("修改后的值:" + new String(data2)); }
五、Zookeeper基于API操作Node节点的更多相关文章
- ZooKeeper 原生API操作
zookeeper客户端和服务器会话的建立是一个异步的过程,也就是说在程序中,程序方法在处理完客户端初始化后立即返回(即程序继续往下执行代码,这样,在大多数情况下并没有真正的构建好一个可用会话,在会话 ...
- ZooKeeper的API操作(二)(通俗易懂)
所需要6个jar包,都是解压zookeeper的tar包后里面的. zookeeper-3.4.10.jar jline-0.094.jar log4j-1.2.16.jar netty- ...
- zookeeper客户端使用第三方(Curator)封装的Api操作节点
1.为什么使用Curator? Curator本身是Netflix公司开源的zookeeper客户端: Curator 提供了各种应用场景的实现封装: curator-framework 提供了f ...
- 六、Java API操作zookeeper节点
目录 前文 pom.xml文件增加依赖 新建java文件:ZookeeperTest GitHub文件下载 前文 一.CentOS7 hadoop3.3.1安装(单机分布式.伪分布式.分布式 二.JA ...
- Kafka(五)Kafka的API操作和拦截器
一 kafka的API操作 1.1 环境准备 1)在eclipse中创建一个java工程 2)在工程的根目录创建一个lib文件夹 3)解压kafka安装包,将安装包libs目录下的jar包拷贝到工程的 ...
- Zookeeper 系列(五)Curator API
Zookeeper 系列(五)Curator API 一.Curator 使用 Curator 框架中使用链式编程风格,易读性更强,使用工程方法创建连接对象使用. (1) CuratorFramewo ...
- zookeeper的java api操作
zookeeper的java api操作 创建会话: Zookeeper(String connectString,int sessionTimeout,Watcher watcher) Zookee ...
- Java API操作ZK node
创建会话 建立简单连接 /** * 测试创建Zk会话 * Created by liuhuichao on 2017/7/25. */ public class ZooKeeper_Construct ...
- Java API操作ZooKeeper
创建会话 package org.zln.zk; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watch ...
随机推荐
- 第14章——高级IO函数
1.套接字超时 套接字IO函数设置超时的方法有三种: (1)调用alarm. (2)select (3)使用SO_RECTIMEO和 SO_SNDTIMEO 选项 上面三种方法适用于输入输出操作(re ...
- cetos6.5 gcc4.8 安装
1.准备源 #安装仓库 wget http://people.centos.org/tru/devtools-2/devtools-2.repo mv devtools-2.repo /etc/yum ...
- python读取excel数据转换成字典
以上面的excel格式,输出字典类型: import xlrddef read_excel_data(): filename = 'E:\学历列表.xls' data = xlrd.open_work ...
- 阻塞队列的take、offer、put、add的一些比较
LinkedBlockingQueue的put,add和offer的区别 最近在学习<<Java并发编程实践>>,有很多java.util.concurrent包下的新类.Li ...
- http请求返回ObjectJson,Array之类转换类型
以下所说的类来自:package com.alibaba.fastjson 1,形如以下返回,其实是个json的map形式的返回 { "success": true, " ...
- 掉电后osdmap丢失无法启动osd的解决方案
前言 本篇讲述的是一个比较极端的故障的恢复场景,在整个集群全部服务器突然掉电的时候,osd里面的osdmap可能会出现没刷到磁盘上的情况,这个时候osdmap的最新版本为空或者为没有这个文件 还有一种 ...
- Mysql_笔记2018.1.29
1.主要数据库 Oracle MySQL Sqlsever 微软 MongoDB (非关系型数据库) 2.MySql 专业词语 1.数据库:一些关联表的集合 2.数据表:表示数据的矩阵 3.列:同ex ...
- [LeetCode题解]109. 有序链表转换二叉搜索树 | 快慢指针 + 递归
题目描述 给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树. 本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1. 示例: 给定的有序链表: ...
- vue实现增删改查(内附源代码)
VUE+Element实现增删改查 @ 目录 VUE+Element实现增删改查 前言 实验步骤 总结: 源代码 前言 &最近因为一些原因,没有更博客,昨天老师布置了一个作业,用vue实现增删 ...
- 整理了 15 道 Spring Boot 高频面试题,看完当面霸!
转载:https://mp.weixin.qq.com/s/fj-DeDfGcIAs8jQbs6bbPA 什么是面霸?就是在面试中,神挡杀神佛挡杀佛,见招拆招,面到面试官自惭形秽自叹不如!松哥希望本文 ...