当前位置: 移动技术网 > IT编程>开发语言>Java > apache zookeeper使用方法实例详解

apache zookeeper使用方法实例详解

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文涉及了apache zookeeper使用方法实例详解的相关知识,接下来我们就看看具体内容。

简介

apache zookeeper 是由 apache hadoop 的 zookeeper 子项目发展而来,现在已经成为了 apache 的顶级项目。zookeeper 为分布式系统提供了高效可靠且易于使用的协同服务,它可以为分布式应用提供相当多的服务,诸如统一命名服务,配置管理,状态同步和组服务等。 zookeeper 接口简单,开发人员不必过多地纠结在分布式系统编程难于处理的同步和一致性问题上,你可以使用 zookeeper 提供的现成(off-the-shelf)服务来实现分布式系统的配置管理,组管理,leader 选举等功能。

英文原文地址:

一个简单的 zookeeper watch 客户端

为了介绍 zookeeper java api 的基本用法,本文将带你如何一步一步实现一个功能简单的  zookeeper 客户端。该 zookeeper 客户端会监视一个你指定 zookeeper 节点 znode, 当被监视的节点发生变化时,客户端会启动或者停止某一程序。

基本要求

该客户端具备四个基本要求:

(1)客户端所带参数:

(2)zookeeper 服务地址。

(3)被监视的 znode 节点名称。

(4)可执行程序及其所带的参数

客户端会获取被监视 znode 节点的数据并启动你所指定的可执行程序。如果被监视的 znode 节点发生改变,客户端重新获取其内容并再次启动你所指定的可执行程序。如果被监视的 znode 节点消失,客户端会杀死可执行程序。

程序设计

一般而言,zookeeper 应用程序分为两部分,其中一部分维护与服务器端的连接,另外一部分监视 znode 节点的数据。在本程序中,executor 类负责维护 zookeeper 连接,datamonitor 类监视 zookeeper 目录树中的数据, 同时,executor 包含了主线程和程序主要的执行逻辑,它负责少量的用户交互,以及与可执行程序的交互,该可执行程序接受你向它传入的参数,并且会根据被监视的 znode 节点的状态变化停止或重启。

executor类

executor 对象是本例程最基本的“容器”,它包括zookeeper 对象和datamonitor对象。

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) {
    }
  }

回忆一下 executor 的任务是根据 zookeeper 中 znode 节点状态改变所触发的事件来启动和停止你在命令行指定的可执行程序, 在上面的代码你可以看到,executor 类在其构造函数中实例化 zookeeper 对象时,将其自身的引用作为 watch 参数传递给 zookeeper 的构造函数,同时它也将其自身的引用作为 datamonitorlistener 参数传递给 datamonitor 的构造函数。executor 本身实现了以下接口:

public class executor implements watcher, runnable, datamonitor.datamonitorlistener {
...

watcher 接口是在zookeeper java api 中定义的。 zookeeper 用它来与“容器”(此处“容器”与上面的 executor 类相似)进行通信,watcher 只支持一个方法,即process(), zookeeper 用该函数来处理主线程可能感兴趣的事件,例如 zookeeper 连接或会话的状态,本例中的“容器” executor只是简单地把事件向下传递给 datamonitor,具体如何处理事件是由 datamonitor 决定的。本文只是简单地描述了如何使用 watcher,通常情况下,executor 或 与 executor 类似的对象拥有 与zookeeper 服务端的连接,但它可以将事件传递给其他对象,并有其它的对象处理该事件。

public void process(watchedevent event) {
    dm.process(event);
  }

datamonitorlistener 接口本身不是zookeeper api 的一部分,它完全是一个自定义的接口,可以说是专门为本程序设计的。datamonitor 对象使用该接口和“容器”(即 executor 类)进行通信,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 类实现该接口,当 executor.exists() 被调用的时候,executor 决定是否启动或停止事先指定的应用程序(回忆一下前文所说的,当 znode 消失时 zookeeper 客户端会杀死该可执行程序)。

当 executor.closing() 被调用的时候,executor 会根据 zookeeper 连接永久性地消失来决定是否关闭自己。

你或许已经猜到,datamonitor 对象根据 zookeeper 状态变化来调用这些方法吧?

以下是 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 类是本程序 zookeeper 逻辑的核心, 它差不多是异步的,并由事件驱动的。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 driven
  zk.exists(znode, true, this, null);
}

调用 zookeeper.exists() 检查指定的 znode 是否存在,并设置监视,传递自身引用作为回调对象,在某种意义上,在 watch 触发时就会引起真实的处理流程。

zookeeper.exists() 操作在端完成时,zookeeper api 会在客户端调用 completion callback

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 errors
    zk.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 handling
      e.printstacktrace();
    } catch (interruptedexception e) {
      return;
    }
  }   
  if ((b == null && b != prevdata)
      || (b != null && !arrays.equals(prevdata, b))) {
    listener.exists(b);
    prevdata = b;
  }
}

上述代码首先检查 znode 是否存在,以及其他重大的不可恢复的错误。如果文件(或者znode)存在,它将从 znode 获取数据,如果状态发生变化再调用 executor 的 exists() 回调函数。注意,getdata 函数本省必须要做任何的异常处理,因为本身就有监视可以处理任何错误:如果节点在调用 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 changed
      switch (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 over
        dead = true;
        listener.closing(keeperexception.code.sessionexpired);
        break;
      }
    } else {
      if (path != null && path.equals(znode)) {
        // something has changed on the node, let's find out
        zk.exists(znode, true, this, null);
      }
    }
    if (chainedwatcher != null) {
      chainedwatcher.process(event);
    }
  }

如果客户端 zookeeper 程序在会话失效时(expired event)重新建立了通信信道(syncconnected event) ,所有的会话监视会自动和服务器进行重连, (zookeeper 3.0.0以上版本会重置之前设置的监视). 更多编程指南请参见 zookeeper watches 。 当 datamonitor 获得了指定 znode 的事件后,它将调用 zookeeper.exists() 来决定究竟发生了什么。

完整的程序:

executor.java:

/**
 * 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 executor
  implements 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();
      }
    }
  }
}

datamonitor.java:

/**
 * 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 driven
    zk.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 changed
      switch (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 over
        dead = true;
        listener.closing(keeperexception.code.sessionexpired);
        break;
      }
    } else {
      if (path != null && path.equals(znode)) {
        // something has changed on the node, let's find out
        zk.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 errors
      zk.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 handling
        e.printstacktrace();
      } catch (interruptedexception e) {
        return;
      }
    }
    if ((b == null && b != prevdata)
        || (b != null && !arrays.equals(prevdata, b))) {
      listener.exists(b);
      prevdata = b;
    }
  }
}

总结

本文关于apache zookeeper使用方法实例详解的介绍就到这里,希望对大家有所帮助。如果有什么问题可以留言,小编会及时回复大家的,感谢大家对移动技术网网站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网