Apache > ZooKeeper
 

ZooKeeper Java示例

一个简单的监视客户端

为了向您介绍ZooKeeper Java API,我们在此开发了一个非常简单的监视客户端。这个ZooKeeper客户端会监视一个znode的变化,并通过启动或停止程序来响应变化。

需求

客户端有四个需求:

程序设计

按照惯例,ZooKeeper应用程序被分为两个单元:一个负责维护连接,另一个负责监控数据。在本应用中,名为Executor的类负责维护ZooKeeper连接,而名为DataMonitor的类则监控ZooKeeper树中的数据。此外,Executor包含主线程和执行逻辑,负责处理少量的用户交互,以及根据znode的状态与你传入作为参数的可执行程序进行交互(根据需求示例会关闭并重启该程序)。

执行器类

Executor对象是示例应用程序的主要容器。它包含上述程序设计中描述的ZooKeeper对象和DataMonitor

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

回想一下,Executor的任务是启动和停止你在命令行中传入的可执行文件。它通过响应ZooKeeper对象触发的事件来完成这一操作。正如你在上面的代码中所看到的,Executor在ZooKeeper构造函数中将自身引用作为Watcher参数传入。同时它也将自身引用作为DataMonitorListener参数传递给DataMonitor构造函数。根据Executor的定义,它同时实现了这两个接口:

public class Executor implements Watcher, Runnable, DataMonitor.DataMonitorListener {
...

Watcher 接口由 ZooKeeper Java API 定义。ZooKeeper 通过该接口与容器进行通信。它仅支持一个方法 process(),ZooKeeper 使用该方法传递主线程可能感兴趣的通用事件,例如 ZooKeeper 连接状态或 ZooKeeper 会话状态。本示例中的 Executor 只是简单地将这些事件转发给 DataMonitor 来决定如何处理。这样做只是为了说明一个惯例:通常由 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节点不再存在时,需要终止可执行程序。

当调用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

调用ZooKeeper.exists()会检查znode是否存在,设置一个监视器,并将自身引用(this)作为完成回调对象传入。从这个意义上说,它启动了整个过程,因为真正的处理发生在监视器被触发时。

注意

不要将完成回调与监视回调混淆。ZooKeeper.exists()的完成回调(恰好是DataMonitor对象中实现的StatCallback.processResult()方法)会在服务器上异步设置监视操作(通过ZooKeeper.exists())完成时被调用。

另一方面,监视器的触发会向Executor对象发送一个事件,因为Executor被注册为ZooKeeper对象的Watcher。

顺便提一下,您可能注意到DataMonitor也可以将自己注册为该特定监视事件的Watcher。这是ZooKeeper 3.0.0新增的功能(支持多个Watcher)。不过在本示例中,DataMonitor并未注册为Watcher。

当服务器上的ZooKeeper.exists()操作完成时,ZooKeeper 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 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 &amp;&amp; b != prevData)
        || (b != null &amp;&amp; !Arrays.equals(prevData, b))) {
        listener.exists(b);</emphasis>
        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事件)之前重新建立与ZooKeeper的通信通道(SyncConnected事件),那么该会话的所有监视器都将自动在服务器端重新建立(监视器自动重置是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;
        }
    }
}