中間件 ZK分佈式專題與Dubbo微服務入門 7-6 curator之usingWatcher

0    課程地址

https://coding.imooc.com/lesson/201.html#mid=12735

 

1    重點關注

1.1    本節內容

curator使用監聽(無論改變多少次,只能監聽一次)

 

1.2    關鍵代碼

 

        cto.client.getData().usingWatcher(new MyCuratorWatcher()).forPath(nodePath);
package com.imooc.curator;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

public class MyWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {
        System.out.println("觸發watcher,節點路徑爲:" + event.getPath());
    }


}

 

 

2    課程內容


 

 


 

3    Coding

3.1    Curator使用監聽

  • 啓動服務端
    進入到
cd /usr/local/zookeeper/bin

 
    重啓zookeeper服務端
./zkServer.sh restart

 

  • 主類
package com.imooc.curator;

import java.util.List;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCache.StartMode;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;

public class CuratorOperator {

    public CuratorFramework client = null;
    public static final String zkServerPath = "172.26.139.4:2181";

    /**
     * 實例化zk客戶端
     */
    public CuratorOperator() {
        /**
         * 同步創建zk示例,原生api是異步的
         * 
         * curator鏈接zookeeper的策略:ExponentialBackoffRetry
         * baseSleepTimeMs:初始sleep的時間
         * maxRetries:最大重試次數
         * maxSleepMs:最大重試時間
         */
//        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5);
        
        /**
         * curator鏈接zookeeper的策略:RetryNTimes
         * n:重試的次數
         * sleepMsBetweenRetries:每次重試間隔的時間
         */
        RetryPolicy retryPolicy = new RetryNTimes(3, 5000);
        
        /**
         * curator鏈接zookeeper的策略:RetryOneTime
         * sleepMsBetweenRetry:每次重試間隔的時間
         */
//        RetryPolicy retryPolicy2 = new RetryOneTime(3000);
        
        /**
         * 永遠重試,不推薦使用
         */
//        RetryPolicy retryPolicy3 = new RetryForever(retryIntervalMs)
        
        /**
         * curator鏈接zookeeper的策略:RetryUntilElapsed
         * maxElapsedTimeMs:最大重試時間
         * sleepMsBetweenRetries:每次重試間隔
         * 重試時間超過maxElapsedTimeMs後,就不再重試
         */
//        RetryPolicy retryPolicy4 = new RetryUntilElapsed(2000, 3000);
        
        client = CuratorFrameworkFactory.builder()
                .connectString(zkServerPath)
                .sessionTimeoutMs(10000).retryPolicy(retryPolicy)
                .namespace("workspace").build();
        client.start();
    }
    
    /**
     * 
     * @Description: 關閉zk客戶端連接
     */
    public void closeZKClient() {
        if (client != null) {
            this.client.close();
        }
    }
    
    public static void main(String[] args) throws Exception {
        // 實例化
        CuratorOperator cto = new CuratorOperator();
        boolean isZkCuratorStarted = cto.client.isStarted();
        System.out.println("當前客戶的狀態:" + (isZkCuratorStarted ? "連接中" : "已關閉"));
        
        // 創建節點
        String nodePath = "/super/imooc";
//        byte[] data = "superme".getBytes();
//        cto.client.create().creatingParentsIfNeeded()
//            .withMode(CreateMode.PERSISTENT)
//            .withACL(Ids.OPEN_ACL_UNSAFE)
//            .forPath(nodePath, data);
        
        // 更新節點數據
//        byte[] newData = "batman".getBytes();
//        cto.client.setData().withVersion(0).forPath(nodePath, newData);
        
        // 刪除節點
//        cto.client.delete()
//                  .guaranteed()                    // 如果刪除失敗,那麼在後端還是繼續會刪除,直到成功
//                  .deletingChildrenIfNeeded()    // 如果有子節點,就刪除
//                  .withVersion(0)
//                  .forPath(nodePath);
        
        
        
        // 讀取節點數據
//        Stat stat = new Stat();
//        byte[] data = cto.client.getData().storingStatIn(stat).forPath(nodePath);
//        System.out.println("節點" + nodePath + "的數據爲: " + new String(data));
//        System.out.println("該節點的版本號爲: " + stat.getVersion());
        
        
        // 查詢子節點
//        List<String> childNodes = cto.client.getChildren()
//                                            .forPath(nodePath);
//        System.out.println("開始打印子節點:");
//        for (String s : childNodes) {
//            System.out.println(s);
//        }
        
                
        // 判斷節點是否存在,如果不存在則爲空
//        Stat statExist = cto.client.checkExists().forPath(nodePath + "/abc");
//        System.out.println(statExist);
        
        
        // watcher 事件  當使用usingWatcher的時候,監聽只會觸發一次,監聽完畢後就銷燬
        cto.client.getData().usingWatcher(new MyCuratorWatcher()).forPath(nodePath);
//        cto.client.getData().usingWatcher(new MyWatcher()).forPath(nodePath);
        
        // 爲節點添加watcher
        // NodeCache: 監聽數據節點的變更,會觸發事件
//        final NodeCache nodeCache = new NodeCache(cto.client, nodePath);
//        // buildInitial : 初始化的時候獲取node的值並且緩存
//        nodeCache.start(true);
//        if (nodeCache.getCurrentData() != null) {
//            System.out.println("節點初始化數據爲:" + new String(nodeCache.getCurrentData().getData()));
//        } else {
//            System.out.println("節點初始化數據爲空...");
//        }
//        nodeCache.getListenable().addListener(new NodeCacheListener() {
//            public void nodeChanged() throws Exception {
//                if (nodeCache.getCurrentData() == null) {
//                    System.out.println("空");
//                    return;
//                }
//                String data = new String(nodeCache.getCurrentData().getData());
//                System.out.println("節點路徑:" + nodeCache.getCurrentData().getPath() + "數據:" + data);
//            }
//        });
        
        
        // 爲子節點添加watcher
        // PathChildrenCache: 監聽數據節點的增刪改,會觸發事件
//        String childNodePathCache =  nodePath;
//        // cacheData: 設置緩存節點的數據狀態
//        final PathChildrenCache childrenCache = new PathChildrenCache(cto.client, childNodePathCache, true);
//        /**
//         * StartMode: 初始化方式
//         * POST_INITIALIZED_EVENT:異步初始化,初始化之後會觸發事件
//         * NORMAL:異步初始化
//         * BUILD_INITIAL_CACHE:同步初始化
//         */
//        childrenCache.start(StartMode.POST_INITIALIZED_EVENT);
//        
//        List<ChildData> childDataList = childrenCache.getCurrentData();
//        System.out.println("當前數據節點的子節點數據列表:");
//        for (ChildData cd : childDataList) {
//            String childData = new String(cd.getData());
//            System.out.println(childData);
//        }
//        
//        childrenCache.getListenable().addListener(new PathChildrenCacheListener() {
//            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
//                if(event.getType().equals(PathChildrenCacheEvent.Type.INITIALIZED)){
//                    System.out.println("子節點初始化ok...");
//                }
//                
//                else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_ADDED)){
//                    String path = event.getData().getPath();
//                    if (path.equals(ADD_PATH)) {
//                        System.out.println("添加子節點:" + event.getData().getPath());
//                        System.out.println("子節點數據:" + new String(event.getData().getData()));
//                    } else if (path.equals("/super/imooc/e")) {
//                        System.out.println("添加不正確...");
//                    }
//                    
//                }else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_REMOVED)){
//                    System.out.println("刪除子節點:" + event.getData().getPath());
//                }else if(event.getType().equals(PathChildrenCacheEvent.Type.CHILD_UPDATED)){
//                    System.out.println("修改子節點路徑:" + event.getData().getPath());
//                    System.out.println("修改子節點數據:" + new String(event.getData().getData()));
//                }
//            }
//        });
        
        Thread.sleep(100000);
        
        cto.closeZKClient();
        boolean isZkCuratorStarted2 = cto.client.isStarted();
        System.out.println("當前客戶的狀態:" + (isZkCuratorStarted2 ? "連接中" : "已關閉"));
    }
    
    public final static String ADD_PATH = "/super/imooc/d";
    
}

 

  • watcher類
package com.imooc.curator;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

public class MyWatcher implements Watcher {

    @Override
    public void process(WatchedEvent event) {
        System.out.println("觸發watcher,節點路徑爲:" + event.getPath());
    }


}

 

  • linux客戶端修改節點(修改多次)
--啓動linux客戶端
zkCli.sh


[zk: localhost:2181(CONNECTED) 0] ls /workspace/super/imooc
[a, b]

--第一次修改
[zk: localhost:2181(CONNECTED) 1] set /workspace/super/imooc 56
cZxid = 0xd5
ctime = Sun Apr 07 06:26:23 CST 2024
mZxid = 0xe0
mtime = Mon Apr 08 06:39:55 CST 2024
pZxid = 0xd9
cversion = 2
dataVersion = 1
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 2
numChildren = 2

--第2次修改
[zk: localhost:2181(CONNECTED) 2] set /workspace/super/imooc 56
cZxid = 0xd5
ctime = Sun Apr 07 06:26:23 CST 2024
mZxid = 0xe2
mtime = Mon Apr 08 06:40:12 CST 2024
pZxid = 0xd9
cversion = 2
dataVersion = 2
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 2
numChildren = 2

--第3次修改
[zk: localhost:2181(CONNECTED) 3] set /workspace/super/imooc 56
cZxid = 0xd5
ctime = Sun Apr 07 06:26:23 CST 2024
mZxid = 0xe3
mtime = Mon Apr 08 06:40:16 CST 2024
pZxid = 0xd9
cversion = 2
dataVersion = 3
aclVersion = 0
ephemeralOwner = 0x0
dataLength = 2
numChildren = 2
[zk: localhost:2181(CONNECTED) 4] 

 


 

  • 打印日誌(只監聽一次)
2024-04-08 06:40:00,026 [main-SendThread(172.26.139.4:2181)] [org.apache.zookeeper.ClientCnxn$SendThread.logStartConnect(ClientCnxn.java:1035)] - [INFO] Opening socket connection to server 172.26.139.4/172.26.139.4:2181. Will not attempt to authenticate using SASL (unknown error)
2024-04-08 06:40:00,029 [main] [org.apache.curator.framework.imps.CuratorFrameworkImpl.start(CuratorFrameworkImpl.java:326)] - [INFO] Default schema
當前客戶的狀態:連接中
2024-04-08 06:40:00,033 [main-SendThread(172.26.139.4:2181)] [org.apache.zookeeper.ClientCnxn$SendThread.primeConnection(ClientCnxn.java:877)] - [INFO] Socket connection established to 172.26.139.4/172.26.139.4:2181, initiating session
2024-04-08 06:40:00,043 [main-SendThread(172.26.139.4:2181)] [org.apache.zookeeper.ClientCnxn$SendThread.onConnected(ClientCnxn.java:1302)] - [INFO] Session establishment complete on server 172.26.139.4/172.26.139.4:2181, sessionid = 0x1003feb17e70006, negotiated timeout = 10000
2024-04-08 06:40:00,051 [main-EventThread] [org.apache.curator.framework.state.ConnectionStateManager.postState(ConnectionStateManager.java:237)] - [INFO] State change: CONNECTED
觸發watcher,節點路徑爲:/super/imooc
2024-04-08 06:41:40,095 [Curator-Framework-0] [org.apache.curator.framework.imps.CuratorFrameworkImpl.backgroundOperationsLoop(CuratorFrameworkImpl.java:924)] - [INFO] backgroundOperationsLoop exiting
2024-04-08 06:41:40,108 [main] [org.apache.zookeeper.ZooKeeper.close(ZooKeeper.java:687)] - [INFO] Session: 0x1003feb17e70006 closed
當前客戶的狀態:已關閉

 




 

 








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章