使用Zookeeper進行開發 —一個基本教程
介紹
在這個指導中,將會告訴你怎樣使用Zookeeper實現屏障和生產者-消費者隊列. 我們將使用到兩個類: Barrier和Queue. 這些實例假定你至少有一個Zookeeper服務器在運行.
它們都使用下面的代碼:
static ZooKeeper zk = null; static Integer mutex; String root; SyncPrimitive(String address) { if(zk == null){ try { System.out.println("Starting ZK:"); zk = new ZooKeeper(address, 3000, this); mutex = new Integer(-1); System.out.println("Finished starting ZK: " + zk); } catch (IOException e) { System.out.println(e.toString()); zk = null; } } } synchronized public void process(WatchedEvent event) { synchronized (mutex) { mutex.notify(); } }
所有類都繼承自SyncPrimitive. 通過這個方法,我們執行SyncPrimitive構造方法是使用通用的步驟. 爲了保持實例簡單,我們創建一個Zookeeper對象,首先我們我們創建一個Barrier和Queue,並且我們創建一個靜態對象來引用這個對象. 之後Barrier和Queue實例會檢查Zookeeper對象是否存在. 或者,我們能夠創建一個Zookeeper對象,並把它傳遞到Barrier和Queue的構造函數中.
我們使用process()方法去處理監聽器觸發的通知. 在下面的內容中,我們會討論watches的代碼實現. 一個監聽者內部構造使Zookeeper能夠通知節點變化到客戶端. 例如,如果一個客戶端正等待其他客戶端離開Barrier,接着他設定一個觀察者,等待對於指定節點的修改,它可以表明這是等待的結束. 一旦我們完車這個例子,這個點會變的特別清楚.
阻塞
barrier是一個元件,它能夠使用一組進程去同步計算的開始和結束. 這個實現的一般方法是有一個barrier節點爲成爲各個處理節點的父節點的目的服務。我們假設這個阻塞節點叫做"/b1". 然後每個進程"p"創建一個節點"/b1/p". 一旦足夠的進程創建相應的節點, 加入的過程就可以開始計算.
在這個例子,每一個進程都會實例化一個Barrier對象,它的構造函數作爲參數:
Zookeeper服務的地址 (例如 "zoo1.foo.com:2181")
Zookeeper阻塞節點的路徑(例如 "/b1")
進程組的個數
Barrier的構造方法通過傳入Zookeeper服務的地址去構造父類. 如果Zookeeper實例不存在,那麼父類就會創建一個Zookeeper實例. 然後Barrier的構造函數會接着在Zookeeper上創建一個阻塞節點,它是所有進程節點的父節點,我們把它稱爲root(注意:不是Zookeeper root "/"的意思)
/** * Barrier的構造方法 * * @param address * @param root * @param size */ Barrier(String address, String root, int size) { super(address); this.root = root; this.size = size; // Create barrier node if (zk != null) { try { Stat s = zk.exists(root, false); if (s == null) { zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } catch (KeeperException e) { System.out .println("Keeper exception when instantiating queue: " + e.toString()); } catch (InterruptedException e) { System.out.println("Interrupted exception"); } } // My node name try { name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString()); } catch (UnknownHostException e) { System.out.println(e.toString()); } }
進入barrier, 一個進程調用enter(). 這個進程在root下創建一個叫節點去表示自己,使用它的主機名稱來表示節點名稱. 然後等待足夠的進程進入Barrier. 進程通過"getChildren()"方法獲得root節點的子節點數量,並且不到一定的數量時,會一直等待. 當root節點變化時接收通知,一個進程必須設置一個監聽者,並通過調用"getChildren()"完成. 在代碼裏,getChildren()方法有兩個參數. 第一個參數是從哪個節點讀取,第二個參數是一個Boolean值,指明是否設置監聽者. 在代碼裏這個flag是true.
/** * Join barrier * * @return * @throws KeeperException * @throws InterruptedException */ boolean enter() throws KeeperException, InterruptedException{ zk.create(root + "/" + name, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); while (true) { synchronized (mutex) { List<String> list = zk.getChildren(root, true); if (list.size() < size) { mutex.wait(); } else { return true; } } } }
注意enter()方法包含兩個異常KeeperException和InterruptedException, 所以需要應用來catch和處理這些異常.
一旦計算完成,一個進程會調用leave()去離開lbarrier. 首先它會刪除所對應的節點,然後會獲取root節點的孩子節點. 如果至少有一個子節點,接着它會等待通知(obs: 注意調用getChildren()方法的第二個參數是true(),含義是爲root節點設置一個監聽者). 收到通知後,它會再次檢查root節點是否有子節點.
/** * Wait until all reach barrier * * @return * @throws KeeperException * @throws InterruptedException */ boolean leave() throws KeeperException, InterruptedException{ zk.delete(root + "/" + name, 0); while (true) { synchronized (mutex) { List<String> list = zk.getChildren(root, true); if (list.size() > 0) { mutex.wait(); } else { return true; } } } } }
生產者和消費隊列
生產者-消費者隊列是由一連串的生產和消費的分佈式的數據結構組成,生產者創建新元素並添加到隊列. 消費者進程從列表中刪除元素,並處理他們. 在這個實現中, 元素是簡單的Integers. 一個隊列由一個根節點表示, 添加一個元素去一個隊列,一個生產者創建一個新的節點, root節點的孩子節點.
以下代碼片段是對象的構造. 與Barrier對象一樣, 它首先調用了父類的構造方法,SyncPrimitive, 如果Zookeeper對象不存在則創建一個Zookeeper對象. 接着會檢查隊列節點是否存在,若不存在則創建.
/** * Constructor of producer-consumer queue * * @param address * @param name */ Queue(String address, String name) { super(address); this.root = name; // Create ZK node name if (zk != null) { try { Stat s = zk.exists(root, false); if (s == null) { zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } catch (KeeperException e) { System.out .println("Keeper exception when instantiating queue: " + e.toString()); } catch (InterruptedException e) { System.out.println("Interrupted exception"); } } }
一個生產者調用produce()添加一個元素到隊列,並傳入一個Interger作爲參數. 添加一個元素到隊列,這個方法創建使用create()創建一個新的節點, 並使用SEQUENCE標誌指示Zookeeper追加根節點順序計數器的值. 用這個方法, 我利用隊列元素上的最終順序,確保隊列最老的元素是下一個消費對象.
/** * Add element to the queue. * * @param i * @return */ boolean produce(int i) throws KeeperException, InterruptedException{ ByteBuffer b = ByteBuffer.allocate(4); byte[] value; // Add child with value i b.putInt(i); value = b.array(); zk.create(root + "/element", value, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); return true; }
消費一個節點,一個消費進程獲得根節點的孩子節點, 讀取節點計數中最小的值,返回該值對應的元素. 注意如果存在衝突,兩個競爭的進程中一個能夠刪除節點,另一個刪除操作會出現異常.
調用getChildren()返回字典順序的孩子節點集合. 由於字段順序不需要組訓計數器值的順序, 我們需要確定元素中最小的. 爲了確定計數器中最小的值,我們會遍歷集合,去除"element"元素獲取最小的值.
/** * 從隊列裏刪除第一個元素 * * @return * @throws KeeperException * @throws InterruptedException */ int consume() throws KeeperException, InterruptedException{ int retvalue = -1; Stat stat = null; // Get the first element available while (true) { synchronized (mutex) { List<String> list = zk.getChildren(root, true); if (list.size() == 0) { System.out.println("Going to wait"); mutex.wait(); } else { Integer min = new Integer(list.get(0).substring(7)); for(String s : list){ Integer tempValue = new Integer(s.substring(7)); //System.out.println("Temporary value: " + tempValue); if(tempValue < min) min = tempValue; } System.out.println("Temporary value: " + root + "/element" + min); byte[] b = zk.getData(root + "/element" + min, false, stat); zk.delete(root + "/element" + min, 0); ByteBuffer buffer = ByteBuffer.wrap(b); retvalue = buffer.getInt(); return retvalue; } } } } }
完整例子
在這部分中,你可以完整執行命令行程序去驗證上面的內容. 使用下面的命令運行它.
ZOOBINDIR="[zookeeper目錄地址]/bin" . "$ZOOBINDIR"/zkEnv.sh java SyncPrimitive [啓動類型 qTest(阻塞)|其他(隊列)] [服務地址 使用ip:port形式] [測試元素個數] [字符串p(生產者)|其他(消費者)]
隊列測試
啓動生產者創建100個元素
java SyncPrimitive qTest localhost 100 p
啓動消費者消費100個元素
java SyncPrimitive qTest localhost 100 c
阻塞測試
啓動對兩個參與者啓動阻塞(開始時,你想加入的參與者可能很多)
java SyncPrimitive bTest localhost 2
Source Listing
import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.List; import java.util.Random; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.ZooDefs.Ids; import org.apache.zookeeper.data.Stat; public class SyncPrimitive implements Watcher { static ZooKeeper zk = null; static Integer mutex; String root; SyncPrimitive(String address) { if(zk == null){ try { System.out.println("Starting ZK:"); zk = new ZooKeeper(address, 3000, this); mutex = new Integer(-1); System.out.println("Finished starting ZK: " + zk); } catch (IOException e) { System.out.println(e.toString()); zk = null; } } //else mutex = new Integer(-1); } synchronized public void process(WatchedEvent event) { synchronized (mutex) { //System.out.println("Process: " + event.getType()); mutex.notify(); } } /** * Barrier */ static public class Barrier extends SyncPrimitive { int size; String name; /** * Barrier constructor * * @param address * @param root * @param size */ Barrier(String address, String root, int size) { super(address); this.root = root; this.size = size; // Create barrier node if (zk != null) { try { Stat s = zk.exists(root, false); if (s == null) { zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } catch (KeeperException e) { System.out .println("Keeper exception when instantiating queue: " + e.toString()); } catch (InterruptedException e) { System.out.println("Interrupted exception"); } } // My node name try { name = new String(InetAddress.getLocalHost().getCanonicalHostName().toString()); } catch (UnknownHostException e) { System.out.println(e.toString()); } } /** * Join barrier * * @return * @throws KeeperException * @throws InterruptedException */ boolean enter() throws KeeperException, InterruptedException{ zk.create(root + "/" + name, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); while (true) { synchronized (mutex) { List<String> list = zk.getChildren(root, true); if (list.size() < size) { mutex.wait(); } else { return true; } } } } /** * Wait until all reach barrier * * @return * @throws KeeperException * @throws InterruptedException */ boolean leave() throws KeeperException, InterruptedException{ zk.delete(root + "/" + name, 0); while (true) { synchronized (mutex) { List<String> list = zk.getChildren(root, true); if (list.size() > 0) { mutex.wait(); } else { return true; } } } } } /** * Producer-Consumer queue */ static public class Queue extends SyncPrimitive { /** * Constructor of producer-consumer queue * * @param address * @param name */ Queue(String address, String name) { super(address); this.root = name; // Create ZK node name if (zk != null) { try { Stat s = zk.exists(root, false); if (s == null) { zk.create(root, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } catch (KeeperException e) { System.out .println("Keeper exception when instantiating queue: " + e.toString()); } catch (InterruptedException e) { System.out.println("Interrupted exception"); } } } /** * Add element to the queue. * * @param i * @return */ boolean produce(int i) throws KeeperException, InterruptedException{ ByteBuffer b = ByteBuffer.allocate(4); byte[] value; // Add child with value i b.putInt(i); value = b.array(); zk.create(root + "/element", value, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL); return true; } /** * Remove first element from the queue. * * @return * @throws KeeperException * @throws InterruptedException */ int consume() throws KeeperException, InterruptedException{ int retvalue = -1; Stat stat = null; // Get the first element available while (true) { synchronized (mutex) { List<String> list = zk.getChildren(root, true); if (list.size() == 0) { System.out.println("Going to wait"); mutex.wait(); } else { Integer min = new Integer(list.get(0).substring(7)); String minNode = list.get(0); for(String s : list){ Integer tempValue = new Integer(s.substring(7)); //System.out.println("Temporary value: " + tempValue); if(tempValue < min) { min = tempValue; minNode = s; } } System.out.println("Temporary value: " + root + "/" + minNode); byte[] b = zk.getData(root + "/" + minNode, false, stat); zk.delete(root + "/" + minNode, 0); ByteBuffer buffer = ByteBuffer.wrap(b); retvalue = buffer.getInt(); return retvalue; } } } } } public static void main(String args[]) { if (args[0].equals("qTest")) queueTest(args); else barrierTest(args); } public static void queueTest(String args[]) { Queue q = new Queue(args[1], "/app1"); System.out.println("Input: " + args[1]); int i; Integer max = new Integer(args[2]); if (args[3].equals("p")) { System.out.println("Producer"); for (i = 0; i < max; i++) try{ q.produce(10 + i); } catch (KeeperException e){ } catch (InterruptedException e){ } } else { System.out.println("Consumer"); for (i = 0; i < max; i++) { try{ int r = q.consume(); System.out.println("Item: " + r); } catch (KeeperException e){ i--; } catch (InterruptedException e){ } } } } public static void barrierTest(String args[]) { Barrier b = new Barrier(args[1], "/b1", new Integer(args[2])); try{ boolean flag = b.enter(); System.out.println("Entered barrier: " + args[2]); if(!flag) System.out.println("Error when entering the barrier"); } catch (KeeperException e){ } catch (InterruptedException e){ } // Generate random integer Random rand = new Random(); int r = rand.nextInt(100); // Loop for rand iterations for (int i = 0; i < r; i++) { try { Thread.sleep(100); } catch (InterruptedException e) { } } try{ b.leave(); } catch (KeeperException e){ } catch (InterruptedException e){ } System.out.println("Left barrier"); } }