ZooKeeper Java Example

2024-05-25 13:18
文章标签 java zookeeper example

本文主要是介绍ZooKeeper Java Example,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

要求

客户端有四个要求:     
这需要作为参数: zookpeer的服务地址、znode的名字、将输出写入到一个文件的名称、一个可执行的参数。  
它与znode获取相关的数据并开始执行。  
如果znode发生变化,重启客户端重新提取内容和可执行文件。  
如果znode消失,客户端可进行线程销毁。

程序设计

一般来说,zookpeer应用被分解成两个部分,一个保持连接,另负责监控数据。在这个应用程序中,这个类称为执行者保持zookpeer联系,和另一个类DataMonitor监控树中的数据。此外,Executor包含主线程和包含执行逻辑。它负责小用户交互是什么,以及交互exectuable计划你在作为参数,该示例根据znode状态进行关闭和重新启动。

// from the Executor class...public static void main(String[] args) {if (args.length < 4) {System.err.println("USAGE: Executor hostPort znode filename program [args ...]");System.exit(2);}String hostPort = args[0];String znode = args[1];String filename = args[2];String exec[] = new String[args.length - 3];System.arraycopy(args, 3, exec, 0, exec.length);try {new Executor(hostPort, znode, filename, exec).run();} catch (Exception e) {e.printStackTrace();}}public Executor(String hostPort, String znode, String filename,String exec[]) throws KeeperException, IOException {this.filename = filename;this.exec = exec;zk = new ZooKeeper(hostPort, 3000, this);dm = new DataMonitor(zk, znode, null, this);}public void run() {try {synchronized (this) {while (!dm.dead) {wait();}}} catch (InterruptedException e) {}}

回想一下,执行程序的工作是启动和停止我传递的名字。它是zookpeer事件的相应对象。正如你所看到的在上面的代码中,执行者通过引用Zookpeer本的构造函数。它还通过引用DataMonitor DataMonitorListener参数的构造函数。没当程序执行的时候,就实现了这两个接口:
public class Executor implements Watcher, Runnable, DataMonitor.DataMonitorListener {
...

Watcher接口是Zookpeer的Java API中定义的。Zookpeer使用它与容器进行通信。它支持一个方法process()。执行程序在这个例子简单地将这些事件转发到DataMonitor决定如何处理它们。它只是为了说明这一点,按照惯例,遗嘱执行人或一些Executor-like对象“拥有”Zookpeer的连接,(后面详细讨论)。
    public void process(WatchedEvent event) {dm.process(event);}

DataMonitorListener接口不是Zookpeer API的一部分。它是一个自定义的interface,为这个示例应用程序而设计的。DataMonitor对象通信使用它回到它的容器,这也是执行程序对象。DataMonitorListener界面如下所示:
public interface DataMonitorListener {/*** The existence status of the node has changed.*/void exists(byte data[]);/*** The ZooKeeper session is no longer valid.* * @param rc* the ZooKeeper reason code*/void closing(int rc);
}

DataMonitor中定义该接口类和执行程序中实现类。当Executor.exists()调用,执行程序决定是否启动或关闭的要求。    
当Executor.closing()调用,执行程序决定是否关闭自己的Zookpeer连接。    
您可能已经猜到,DataMonitor的对象调用这些方法,以应对变化的Zookpeer状态。    
以下是Executor的DataMonitorListener.exists实现()和DataMonitorListener.closing:
public void exists( byte[] data ) {if (data == null) {if (child != null) {System.out.println("Killing process");child.destroy();try {child.waitFor();} catch (InterruptedException e) {}}child = null;} else {if (child != null) {System.out.println("Stopping child");child.destroy();try {child.waitFor();} catch (InterruptedException e) {e.printStackTrace();}}try {FileOutputStream fos = new FileOutputStream(filename);fos.write(data);fos.close();} catch (IOException e) {e.printStackTrace();}try {System.out.println("Starting child");child = Runtime.getRuntime().exec(exec);new StreamWriter(child.getInputStream(), System.out);new StreamWriter(child.getErrorStream(), System.err);} catch (IOException e) {e.printStackTrace();}}
}public void closing(int rc) {synchronized (this) {notifyAll();}
}

DataMonitor类

DataMonitor类是Zookpeer的主要逻辑。它主要是异步和事件驱动的。DataMonitor构造函数:
public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,DataMonitorListener listener) {this.zk = zk;this.znode = znode;this.chainedWatcher = chainedWatcher;this.listener = listener;// Get things started by checking if the node exists. We are going// to be completely event drivenzk.exists(znode, true, this, null);
}

调用ZooKeeper.exists()检查znode的存在,设置一个坚挺,和通过引用本身(这)作为完成回调对象。在这个意义上,它开始做事了,因为真正的watch被触发。
Don't confuse the completion callback with the watch callback. The ZooKeeper.exists() completion callback, which happens to be the method StatCallback.processResult() implemented in the DataMonitor object, is invoked when the asynchronous setting of the watch operation (by ZooKeeper.exists()) completes on the server.The triggering of the watch, on the other hand, sends an event to the Executor object, since the Executor registered as the Watcher of the ZooKeeper object.As an aside, you might note that the DataMonitor could also register itself as the Watcher for this particular watch event. This is new to ZooKeeper 3.0.0 (the support of multiple Watchers). In this example, however, DataMonitor does not register as the Watcher.

当ZooKeeper.exists()操作在服务器上完成,Zookpeer API回调客户端:
public void processResult(int rc, String path, Object ctx, Stat stat) {boolean exists;switch (rc) {case Code.Ok:exists = true;break;case Code.NoNode:exists = false;break;case Code.SessionExpired:case Code.NoAuth:dead = true;listener.closing(rc);return;default:// Retry errorszk.exists(znode, true, this, null);return;}byte b[] = null;if (exists) {try {b = zk.getData(znode, false, null);} catch (KeeperException e) {// We don't need to worry about recovering now. The watch// callbacks will kick off any exception handlinge.printStackTrace();} catch (InterruptedException e) {return;}}     if ((b == null && b != prevData)|| (b != null && !Arrays.equals(prevData, b))) {listener.exists(b);prevData = b;}
}

代码首先检查znode存在的错误代码,致命错误,可恢复错误。如果文件(或znode)存在,它从znode获取数据,如果状态改变,调用执行者的exist()。注意,它没有任何异常处理getData调用,因为 watches等待任何可能导致一个错误:如果节点被删除之前调用ZooKeeper.getData(),观察事件的ZooKeeper.exists()触发回调;如果有一个通信错误,当连接返回后一个连接监听事件触发。    

最后,注意DataMonitor过程观察事件:
 public void process(WatchedEvent event) {String path = event.getPath();if (event.getType() == Event.EventType.None) {// We are are being told that the state of the// connection has changedswitch (event.getState()) {case SyncConnected:// In this particular example we don't need to do anything// here - watches are automatically re-registered with // server and any watches triggered while the client was // disconnected will be delivered (in order of course)break;case Expired:// It's all overdead = true;listener.closing(KeeperException.Code.SessionExpired);break;}} else {if (path != null && path.equals(znode)) {// Something has changed on the node, let's find outzk.exists(znode, true, this, null);}}if (chainedWatcher != null) {chainedWatcher.process(event);}}

如果客户端Zookpeer库可以重建通信通道(SyncConnected事件)会话过期前Zookpeer(过期事件)的所有会话的监听会自动重新建立。

完整源代码清单

/*** A simple example program to use DataMonitor to start and* stop executables based on a znode. The program watches the* specified znode and saves the data that corresponds to the* znode in the filesystem. It also starts the specified program* with the specified arguments when the znode exists and kills* the program if the znode goes away.*/
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;public class Executorimplements Watcher, Runnable, DataMonitor.DataMonitorListener
{String znode;DataMonitor dm;ZooKeeper zk;String filename;String exec[];Process child;public Executor(String hostPort, String znode, String filename,String exec[]) throws KeeperException, IOException {this.filename = filename;this.exec = exec;zk = new ZooKeeper(hostPort, 3000, this);dm = new DataMonitor(zk, znode, null, this);}/*** @param args*/public static void main(String[] args) {if (args.length < 4) {System.err.println("USAGE: Executor hostPort znode filename program [args ...]");System.exit(2);}String hostPort = args[0];String znode = args[1];String filename = args[2];String exec[] = new String[args.length - 3];System.arraycopy(args, 3, exec, 0, exec.length);try {new Executor(hostPort, znode, filename, exec).run();} catch (Exception e) {e.printStackTrace();}}/**************************************************************************** We do process any events ourselves, we just need to forward them on.** @see org.apache.zookeeper.Watcher#process(org.apache.zookeeper.proto.WatcherEvent)*/public void process(WatchedEvent event) {dm.process(event);}public void run() {try {synchronized (this) {while (!dm.dead) {wait();}}} catch (InterruptedException e) {}}public void closing(int rc) {synchronized (this) {notifyAll();}}static class StreamWriter extends Thread {OutputStream os;InputStream is;StreamWriter(InputStream is, OutputStream os) {this.is = is;this.os = os;start();}public void run() {byte b[] = new byte[80];int rc;try {while ((rc = is.read(b)) > 0) {os.write(b, 0, rc);}} catch (IOException e) {}}}public void exists(byte[] data) {if (data == null) {if (child != null) {System.out.println("Killing process");child.destroy();try {child.waitFor();} catch (InterruptedException e) {}}child = null;} else {if (child != null) {System.out.println("Stopping child");child.destroy();try {child.waitFor();} catch (InterruptedException e) {e.printStackTrace();}}try {FileOutputStream fos = new FileOutputStream(filename);fos.write(data);fos.close();} catch (IOException e) {e.printStackTrace();}try {System.out.println("Starting child");child = Runtime.getRuntime().exec(exec);new StreamWriter(child.getInputStream(), System.out);new StreamWriter(child.getErrorStream(), System.err);} catch (IOException e) {e.printStackTrace();}}}
}

/*** A simple class that monitors the data and existence of a ZooKeeper* node. It uses asynchronous ZooKeeper APIs.*/
import java.util.Arrays;import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.AsyncCallback.StatCallback;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.data.Stat;public class DataMonitor implements Watcher, StatCallback {ZooKeeper zk;String znode;Watcher chainedWatcher;boolean dead;DataMonitorListener listener;byte prevData[];public DataMonitor(ZooKeeper zk, String znode, Watcher chainedWatcher,DataMonitorListener listener) {this.zk = zk;this.znode = znode;this.chainedWatcher = chainedWatcher;this.listener = listener;// Get things started by checking if the node exists. We are going// to be completely event drivenzk.exists(znode, true, this, null);}/*** Other classes use the DataMonitor by implementing this method*/public interface DataMonitorListener {/*** The existence status of the node has changed.*/void exists(byte data[]);/*** The ZooKeeper session is no longer valid.** @param rc*                the ZooKeeper reason code*/void closing(int rc);}public void process(WatchedEvent event) {String path = event.getPath();if (event.getType() == Event.EventType.None) {// We are are being told that the state of the// connection has changedswitch (event.getState()) {case SyncConnected:// In this particular example we don't need to do anything// here - watches are automatically re-registered with // server and any watches triggered while the client was // disconnected will be delivered (in order of course)break;case Expired:// It's all overdead = true;listener.closing(KeeperException.Code.SessionExpired);break;}} else {if (path != null && path.equals(znode)) {// Something has changed on the node, let's find outzk.exists(znode, true, this, null);}}if (chainedWatcher != null) {chainedWatcher.process(event);}}public void processResult(int rc, String path, Object ctx, Stat stat) {boolean exists;switch (rc) {case Code.Ok:exists = true;break;case Code.NoNode:exists = false;break;case Code.SessionExpired:case Code.NoAuth:dead = true;listener.closing(rc);return;default:// Retry errorszk.exists(znode, true, this, null);return;}byte b[] = null;if (exists) {try {b = zk.getData(znode, false, null);} catch (KeeperException e) {// We don't need to worry about recovering now. The watch// callbacks will kick off any exception handlinge.printStackTrace();} catch (InterruptedException e) {return;}}if ((b == null && b != prevData)|| (b != null && !Arrays.equals(prevData, b))) {listener.exists(b);prevData = b;}}
}


这篇关于ZooKeeper Java Example的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1001608

相关文章

SpringBoot整合liteflow的详细过程

《SpringBoot整合liteflow的详细过程》:本文主要介绍SpringBoot整合liteflow的详细过程,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋...  liteflow 是什么? 能做什么?总之一句话:能帮你规范写代码逻辑 ,编排并解耦业务逻辑,代码

JavaSE正则表达式用法总结大全

《JavaSE正则表达式用法总结大全》正则表达式就是由一些特定的字符组成,代表的是一个规则,:本文主要介绍JavaSE正则表达式用法的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录常用的正则表达式匹配符正则表China编程达式常用的类Pattern类Matcher类PatternSynta

Spring Security中用户名和密码的验证完整流程

《SpringSecurity中用户名和密码的验证完整流程》本文给大家介绍SpringSecurity中用户名和密码的验证完整流程,本文结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定... 首先创建了一个UsernamePasswordAuthenticationTChina编程oken对象,这是S

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Spring 框架之Springfox使用详解

《Spring框架之Springfox使用详解》Springfox是Spring框架的API文档工具,集成Swagger规范,自动生成文档并支持多语言/版本,模块化设计便于扩展,但存在版本兼容性、性... 目录核心功能工作原理模块化设计使用示例注意事项优缺点优点缺点总结适用场景建议总结Springfox 是

在Spring Boot中集成RabbitMQ的实战记录

《在SpringBoot中集成RabbitMQ的实战记录》本文介绍SpringBoot集成RabbitMQ的步骤,涵盖配置连接、消息发送与接收,并对比两种定义Exchange与队列的方式:手动声明(... 目录前言准备工作1. 安装 RabbitMQ2. 消息发送者(Producer)配置1. 创建 Spr

java向微信服务号发送消息的完整步骤实例

《java向微信服务号发送消息的完整步骤实例》:本文主要介绍java向微信服务号发送消息的相关资料,包括申请测试号获取appID/appsecret、关注公众号获取openID、配置消息模板及代码... 目录步骤1. 申请测试系统2. 公众号账号信息3. 关注测试号二维码4. 消息模板接口5. Java测试