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

相关文章

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

java中新生代和老生代的关系说明

《java中新生代和老生代的关系说明》:本文主要介绍java中新生代和老生代的关系说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、内存区域划分新生代老年代二、对象生命周期与晋升流程三、新生代与老年代的协作机制1. 跨代引用处理2. 动态年龄判定3. 空间分

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

Java 线程安全与 volatile与单例模式问题及解决方案

《Java线程安全与volatile与单例模式问题及解决方案》文章主要讲解线程安全问题的五个成因(调度随机、变量修改、非原子操作、内存可见性、指令重排序)及解决方案,强调使用volatile关键字... 目录什么是线程安全线程安全问题的产生与解决方案线程的调度是随机的多个线程对同一个变量进行修改线程的修改操