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()and的实现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 类具有 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

检查 znode 是否存在的调用ZooKeeper.exists(),设置监视,并将对自身 ( this) 的引用作为完成回调对象传递。从这个意义上说,它开始了事情,因为真正的处理发生在手表被触发时。

笔记

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

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

顺便说一句,您可能会注意到 DataMonitor 还可以将自己注册为此特定监视事件的监视程序。这是 ZooKeeper 3.0.0 的新功能(支持多个观察者)。但是,在此示例中,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 事件),则所有会话的手表将自动与服务器重新建立(手表的自动重置是新的动物园管理员 3.0.0)。有关这方面的更多信息,请参阅程序员指南中的ZooKeeper Watches。在这个函数中稍微低一点,当 DataMonitor 得到一个 znode 的事件时,它会调用ZooKeeper.exists()以找出发生了什么变化。

完整的源清单

执行器.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();
            }
        }
    }
}

数据监视器.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;
        }
    }
}