最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

ZooKeeper官方文檔之Java客戶端開發(fā)案例翻譯

 更新時間:2022年01月27日 15:08:18   作者:愛碼叔(稀有氣體)  
網(wǎng)上有很多ZooKeeper的java客戶端例子,我也看過很多,不過大部分寫的都不好,有各種問題。兜兜轉(zhuǎn)轉(zhuǎn)還是覺得官方給的例子最為經(jīng)典,在學習之余翻譯下來,供朋友們參考

官網(wǎng)原文標題《ZooKeeper Java Example》

官網(wǎng)原文地址:http://zookeeper.apache.org/doc/current/javaExample.html#sc_completeSourceCode

針對本篇翻譯文章,我還有一篇對應的筆記《ZooKeeper官方Java例子解讀》,如果對官網(wǎng)文檔理解有困難,可以結(jié)合我的筆記理解。

一個簡單的監(jiān)聽客戶端

通過開發(fā)一個非常簡單的監(jiān)聽客戶端,為你介紹ZooKeeper的Java API。此ZooKeeper的客戶端,監(jiān)聽ZooKeeper中node的變化并做出響應。

需求

這個客戶端有如下四個需求:

1、它接收如下參數(shù):

  • ZooKeeper服務的地址
  • 被監(jiān)控的znode的名稱
  • 可執(zhí)行命令參數(shù)

2、它會取得znode上關(guān)聯(lián)的數(shù)據(jù),然后執(zhí)行命令

3、如果znode變化,客戶端重新拉取數(shù)據(jù),再次執(zhí)行命令

4、如果znode消失了,客戶端殺掉進行的執(zhí)行命令。

程序設計

一般我們會這么做,把ZooKeeper的程序分成兩個單元,一個維護連接,另外一個監(jiān)控數(shù)據(jù)。本程序中Executor類維護ZooKeeper的連接,DataMonitor監(jiān)控ZooKeeper的數(shù)據(jù)。同時,Executor維護主線程以及執(zhí)行邏輯。它負責對用戶的交互做出響應,這里的交互既指根據(jù)你傳入?yún)?shù)做出響應,也指根據(jù)znode的狀態(tài),關(guān)閉和重啟。

Executor類

// 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的工作是啟停通過命令行傳入的執(zhí)行命令。他通過響應ZooKeeper對象觸發(fā)的事件來實現(xiàn)。就像上面的代碼,在ZooKeeper的構(gòu)造器中,Executor傳遞自己的引用作為watcher參數(shù)。同時,他傳遞自己的引用作為DataMonitorLisrener參數(shù)給DataMonitor構(gòu)造器。在Executor定義中,實現(xiàn)了這些接口。

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

ZooKeeper的Java API定義了Watcher接口。ZooKeeper用它來反饋給它的持有者。它僅支持一個方法process(),ZooKeeper用它來反饋主線程感興趣的通用事件,例如ZooKeeper的連接狀態(tài),或者ZooKeeper session的狀態(tài)。例子中的Executor只是簡單的把事件傳遞給DataMonitor,由DataMonitor來決定怎么處理。為了方便,Executor或者其他的類似Executor的對象持有ZooKeeper連接,但是可以很自由的把事件委派給其他對象。它也用此作為觸發(fā)watch事件的默認渠道。

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類實現(xiàn)。當調(diào)用Executor.exists(),Executor根據(jù)需求決定是否啟動還是關(guān)閉?;貞浺幌拢枨筇岬疆攝node不再存在時,殺掉進行中的執(zhí)行命令。

當調(diào)用Executor.closing(),作為對ZooKeeper連接永久消失的響應,Executor決定是否關(guān)閉它自己。

就像你可能猜想的那樣,,作為對ZooKeeper狀態(tài)變化的響應,這些方法的調(diào)用者是DataMonitor。

下面是Exucutor中 DataMonitorListener.exists()和DataMonitorListener.closing()的實現(xiàn)

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類中。他是異步和事件驅(qū)動的。DataMonitor在構(gòu)造函數(shù)中完成啟動。

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

對zk.exists()的調(diào)用,會檢查znode是否存在,設置watch,傳遞他自己的引用作為完成后的回調(diào)對象。這意味著,當watch被引發(fā),真正的處理才開始。

Note

不要把完成回調(diào)和watch回調(diào)搞混。ZooKeeper.exists()完成時的回調(diào),發(fā)生在DataMonitor對象實現(xiàn)的的StatCallback.processResult()方法中,調(diào)用發(fā)生在server上異步的watch設置操作(通過zk.exists())完成時。

另一邊,watch觸發(fā)時,給Executor對象發(fā)送了一個事件,因為Executor注冊成為ZooKeeper對象的一個watcher。

你可能注意到DataMonitor也可以注冊它自己作為這個特定事件的watcher。這是ZooKeeper 3.0.0中加入的(多watcher的支持)。在這個例子中,DataMonitor并沒有注冊為watcher(譯者:這里指zookeeper對象的watcher)。

當ZooKeeper.exists()在server上執(zhí)行完成。ZooKeeper API將在客戶端發(fā)起這個完成回調(diào)

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取得數(shù)據(jù),如果狀態(tài)發(fā)生改變,調(diào)用Executor的exists回調(diào)。不需要為getData做任何異常處理。因為它為任何可能引發(fā)錯誤的情況設置了監(jiān)控:如果在調(diào)用ZooKeeper.getData()前,node被刪除了,通過ZooKeeper.exists設置的監(jiān)聽事件被觸發(fā)回調(diào);如果發(fā)生了通信錯誤,當連接恢復時,連接的監(jiān)聽事件被觸發(fā)。

最后,看一下DataMonitor是如何處理監(jiān)聽事件的:

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

在session過期前,如果客戶端zookeeper類庫能重新發(fā)布和zookeeper的連接通道(SyncConnected event),session的所有watch將會重新發(fā)布。(zookeeper 3.0.0開始)。學習開發(fā)手冊中的ZooKeeper Watches。繼續(xù)往下講,當DataMonitor從znode收到事件,他將會調(diào)用zookeeper.exists(),來找出發(fā)生了什么變化。

完整代碼清單

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;
        }
    }
}

以上就是Java客戶端開發(fā)案例ZooKeeper官方文檔翻譯的詳細內(nèi)容,更多關(guān)于java開發(fā)案例ooKeeper文檔翻譯的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • java使用rmi傳輸大文件示例分享

    java使用rmi傳輸大文件示例分享

    由于在rmi中無法傳輸文件流,可以先用FileInputStream將文件讀到一個Byte數(shù)組中,然后把這個Byte數(shù)組作為參數(shù)傳進RMI的方法中,然后在服務器端將Byte數(shù)組還原為outputStream,這樣就能通過RMI 來傳輸文件了,下面我們來看實例
    2014-01-01
  • java?讀寫?ini?配置文件的示例代碼

    java?讀寫?ini?配置文件的示例代碼

    這篇文章主要介紹了java?讀寫?ini?配置文件,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2022-01-01
  • spring boot+ redis 接口訪問頻率限制的實現(xiàn)

    spring boot+ redis 接口訪問頻率限制的實現(xiàn)

    這篇文章主要介紹了spring boot+ redis 接口訪問頻率限制的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-01-01
  • java boolean占用內(nèi)存大小說明

    java boolean占用內(nèi)存大小說明

    這篇文章主要介紹了java boolean占用內(nèi)存大小,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Java整合騰訊云短信發(fā)送實例代碼

    Java整合騰訊云短信發(fā)送實例代碼

    大家好,本篇文章主要講的是Java整合騰訊云短信發(fā)送實例代碼,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • Java中Spring Boot+Socket實現(xiàn)與html頁面的長連接實例詳解

    Java中Spring Boot+Socket實現(xiàn)與html頁面的長連接實例詳解

    這篇文章主要介紹了Java中Spring Boot+Socket實現(xiàn)與html頁面的長連接實例詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-07-07
  • springboot項目mapper無法自動裝配未找到?UserMapper?類型的Bean解決辦法

    springboot項目mapper無法自動裝配未找到?UserMapper?類型的Bean解決辦法

    這篇文章給大家介紹了springboot項目mapper無法自動裝配,未找到?‘userMapper‘?類型的?Bean解決辦法(含報錯原因),文章通過圖文結(jié)合的方式介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下
    2024-02-02
  • 線程池中使用spring aop事務增強

    線程池中使用spring aop事務增強

    這篇文章主要介紹了線程池中使用spring aop事務增強,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • 淺析Java和Scala中的Future

    淺析Java和Scala中的Future

    這篇文章主要介紹了Java和Scala中的Future的相關(guān)資料,需要的朋友可以參考下
    2017-10-10
  • Java多線程yield心得分享

    Java多線程yield心得分享

    前幾天復習了一下多線程,發(fā)現(xiàn)有許多網(wǎng)上講的都很抽象,所以,自己把網(wǎng)上的一些案例總結(jié)了一下
    2013-12-12

最新評論

林甸县| 盈江县| 富宁县| 西城区| 扶绥县| 三门县| 祁门县| 安仁县| 夏河县| 环江| 彰化县| 霍林郭勒市| 徐汇区| 娱乐| 台南县| 桓台县| 巨野县| 余干县| 印江| 彭泽县| 丘北县| 逊克县| 保靖县| 乌拉特前旗| 宿州市| 久治县| 虞城县| 岑巩县| 武城县| SHOW| 沛县| 楚雄市| 锡林郭勒盟| 会泽县| 邓州市| 莱州市| 柳江县| 高要市| 台北市| 伊川县| 嘉兴市|