Zookeeper watch機制原理

酒醉夢醒發表於2020-10-30

Zookeeper watch機制原理

準備工作

經過上一小節的學習我們知道ZookeeperServerMain是單機版的伺服器主類
在這裡插入圖片描述

我們可以自己寫一個ZkClient類

public class ZkClient {
	public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        final CountDownLatch countDownLatch=new CountDownLatch(1);
        ZooKeeper zooKeeper=
                new ZooKeeper("localhost:2182",
                        4000, new Watcher() {
                    @Override
                    public void process(WatchedEvent event) {
                        System.out.println(event);
                        if(Event.KeeperState.SyncConnected==event.getState()){
                            //如果收到了服務端的響應事件,連線成功
                            countDownLatch.countDown();
                        }
                    }
                });
        countDownLatch.await();
        //CONNECTED
        System.out.println(zooKeeper.getState());
		
        byte[] data = zooKeeper.getData("/lry",new Watcher(){
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event);
            }
        },new Stat());

        System.out.println(new String(data));
        System.in.read();
        //只有getData,getChildren,exist這三個api有watcher
    }
}

我們還需要一個控制檯可以輸入命令的主類,ZookeeperMain
在這裡插入圖片描述
進入ZookeeperMain的run方法,把如下程式碼註釋

//                String line;
//                Method readLine = consoleC.getMethod("readLine", String.class);
//                while ((line = (String)readLine.invoke(console, getPrompt())) != null) {
//                    executeLine(line);
//                }

並且加上一行程式碼
在這裡插入圖片描述
這樣先啟動ZookeeperServerMain,在啟動ZookeeperMain我們就可以在控制檯手打命令了

watch示例

菜鳥要飛-zookeeper watch

菜鳥上說的很簡潔明瞭,但是有一些小點限於篇幅沒有說到,比如:

  1. 客戶端傳送給伺服器的包不包括watcher物件資訊?
  2. pendingQueue在watch機制中的作用?
  3. 為什麼只需要request.setWatch(true),而不需要把watcher物件傳送給伺服器?
  4. 伺服器在收到修改命令後觸發triggerWatch方法傳送xid=-1的事件給客戶端後,客戶端是如何從pendingQueue拿出watcher物件,然後回撥process方法的?

在這裡插入圖片描述

原始碼解析

//todo

相關文章