ZooKeeper官方文檔之Java客戶端開發(fā)案例翻譯
官網(wǎng)原文標題《ZooKeeper Java Example》
官網(wǎng)原文地址:http://zookeeper.apache.org/doc/current/javaExample.html#sc_completeSourceCode
針對本篇翻譯文章,我還有一篇對應的筆記《ZooKeeper官方Java例子解讀》,如果對官網(wǎng)文檔理解有困難,可以結合我的筆記理解。
一個簡單的監(jiān)聽客戶端
通過開發(fā)一個非常簡單的監(jiān)聽客戶端,為你介紹ZooKeeper的Java API。此ZooKeeper的客戶端,監(jiān)聽ZooKeeper中node的變化并做出響應。
需求
這個客戶端有如下四個需求:
1、它接收如下參數(shù):
- ZooKeeper服務的地址
- 被監(jiān)控的znode的名稱
- 可執(zhí)行命令參數(shù)
2、它會取得znode上關聯(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),關閉和重啟。
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的構造器中,Executor傳遞自己的引用作為watcher參數(shù)。同時,他傳遞自己的引用作為DataMonitorLisrener參數(shù)給DataMonitor構造器。在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)。當調用Executor.exists(),Executor根據(jù)需求決定是否啟動還是關閉?;貞浺幌拢枨筇岬疆攝node不再存在時,殺掉進行中的執(zhí)行命令。
當調用Executor.closing(),作為對ZooKeeper連接永久消失的響應,Executor決定是否關閉它自己。
就像你可能猜想的那樣,,作為對ZooKeeper狀態(tài)變化的響應,這些方法的調用者是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類中。他是異步和事件驅動的。DataMonitor在構造函數(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()的調用,會檢查znode是否存在,設置watch,傳遞他自己的引用作為完成后的回調對象。這意味著,當watch被引發(fā),真正的處理才開始。
Note
不要把完成回調和watch回調搞混。ZooKeeper.exists()完成時的回調,發(fā)生在DataMonitor對象實現(xiàn)的的StatCallback.processResult()方法中,調用發(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ā)起這個完成回調
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ā)生改變,調用Executor的exists回調。不需要為getData做任何異常處理。因為它為任何可能引發(fā)錯誤的情況設置了監(jiān)控:如果在調用ZooKeeper.getData()前,node被刪除了,通過ZooKeeper.exists設置的監(jiān)聽事件被觸發(fā)回調;如果發(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收到事件,他將會調用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官方文檔翻譯的詳細內容,更多關于java開發(fā)案例ooKeeper文檔翻譯的資料請關注腳本之家其它相關文章!
相關文章
spring boot+ redis 接口訪問頻率限制的實現(xiàn)
這篇文章主要介紹了spring boot+ redis 接口訪問頻率限制的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01
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解決辦法(含報錯原因),文章通過圖文結合的方式介紹的非常詳細,具有一定的參考價值,需要的朋友可以參考下2024-02-02

