Curator Framework操作zookeeper(2)-節點監聽

Curator Framework操作zookeeper(1)-基本操作

1 SessionConnectionStateListener

/**
 * 監聽Session連接狀態
 */
public class SessionConnectionStateListener  implements ConnectionStateListener
{
    private static final Logger log = LoggerFactory.getLogger(SessionConnectionStateListener.class);

    public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState)
    {
        if (connectionState == ConnectionState.LOST)
        {
            log.info("ConnectionState: lost");
            try
            {
                for (;;)
                {
                    if (curatorFramework.getZookeeperClient().blockUntilConnectedOrTimedOut())
                    {
                        log.info("reconnection: success");
                        break;
                    }
                }
                return;
            }
            catch (InterruptedException e)
            {
                log.info("reconnection: failure");
            }
            catch (Exception e)
            {
                log.info("reconnection: failure");
            }
        }
    }
}

2 AbstractNodeCacheListener 和 MyNodeCacheListener

public abstract class AbstractNodeCacheListener  implements NodeCacheListener {

    private static final Logger log = LoggerFactory.getLogger(MyNodeCacheListener.class);

    private NodeCache nodeCache;

    public AbstractNodeCacheListener(){

    }

    public AbstractNodeCacheListener(NodeCache nodeCache) {
        this.nodeCache = nodeCache;
    }

    public NodeCache getNodeCache() {
        return nodeCache;
    }

    public void setNodeCache(NodeCache nodeCache) {
        this.nodeCache = nodeCache;
    }
}

MyNodeCacheListener

/**
 * 監聽本節點
 */
public class MyNodeCacheListener extends AbstractNodeCacheListener {
    private static final Logger log = LoggerFactory.getLogger(MyNodeCacheListener.class);

    public MyNodeCacheListener() {
         super();
    }

    public MyNodeCacheListener(NodeCache nodeCache) {
        super(nodeCache);
    }

    @Override
    public void nodeChanged() throws Exception {
        ChildData childData = this.getNodeCache().getCurrentData();
        /**
         * 創建和更新 childData 不爲 null
         * 刪除  childData 爲 null
         */
        if(childData != null){
            log.info("Path: " + childData.getPath());
            log.info("Stat:" + childData.getStat());
            log.info("Data: "+ new String(childData.getData(),"utf-8"));
        }
    }
}

3 MyPathChildrenCacheListener

/**
 * 監聽節點的所有子目錄
 */
public class MyPathChildrenCacheListener implements PathChildrenCacheListener {

    private static final Logger log = LoggerFactory.getLogger(MyPathChildrenCacheListener.class);

    @Override
    public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
        switch (event.getType()) {
            case INITIALIZED:
                //必須異步模式 PathChildrenCache.StartMode.POST_INITIALIZED_EVENT
                log.info("子節點初始化成功");
                break;
            case CHILD_ADDED:
                log.info("添加子節點路徑:" + event.getData().getPath());
                log.info("添加子節點數據:" + new String(event.getData().getData()));
                break;
            case CHILD_UPDATED:
                log.info("修改子節點路徑:" + event.getData().getPath());
                log.info("修改子節點數據:" + new String(event.getData().getData()));
                break;
            case CHILD_REMOVED:
                log.info("刪除子節點:" + event.getData().getPath());
                break;
            case CONNECTION_LOST:
                log.info("連接丟失");
                break;
            case CONNECTION_SUSPENDED:
                log.info("連接被掛起");
                break;
            case CONNECTION_RECONNECTED:
                log.info("恢復連接");
                break;
        }
    }
}

4 MyTreeCacheListener

/**
 * 監聽本節點和子目錄
 */
public class MyTreeCacheListener implements TreeCacheListener {

    private static final Logger log = LoggerFactory.getLogger(MyTreeCacheListener.class);

    @Override
    public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
        ChildData childData = event.getData();
        if (childData != null) {
            //System.out.println("Path: " + childData.getPath());
            //System.out.println("Stat:" + childData.getStat());
            //System.out.println("Data: " + new String(childData.getData()));
        }
        switch (event.getType()) {
            case INITIALIZED:
                log.info("節點初始化成功");
                break;
            case NODE_ADDED:
                log.info("添加節點路徑:" + event.getData().getPath());
                log.info("節點數據:" + new String(event.getData().getData()));
                break;
            case NODE_UPDATED:
                log.info("修改節點路徑:" + event.getData().getPath());
                log.info("修改節點數據:" + new String(event.getData().getData()));
                break;
            case NODE_REMOVED:
                log.info("刪除節點:" + event.getData().getPath());
                break;
            case CONNECTION_LOST:
                System.out.println("連接丟失");
                break;
            case CONNECTION_SUSPENDED:
                System.out.println("連接被掛起");
                break;
            case CONNECTION_RECONNECTED:
                System.out.println("恢復連接");
                break;
        }
    }
}

5 測試代碼

 public static void testNodeCacheListener(){
        ZkUtil.initialize();
        String parent = "/zkconfig";
        String child = "chynode";
        String path = parent + "/" + child;

        MyNodeCacheListener myNodeCacheListener=new MyNodeCacheListener();

        //註冊當前節點監聽器
        ZkUtil.registerNodeCacheListener(path,myNodeCacheListener);

        //如果不存在節點增加節點
        try {
            if (!ZkUtil.checkExist(path)) {
                ZkUtil.addNode(parent, child, "chy");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void testPathChildrenCacheListener(){
        ZkUtil.initialize();
        String parent = "/zkconfig";
        String child = "chynode";
        String path = parent + "/" + child;

        MyPathChildrenCacheListener myPathChildrenCacheListener=new MyPathChildrenCacheListener();

        //子節點監聽器
        ZkUtil.registerPathChildListener(parent,myPathChildrenCacheListener);

        //如果不存在節點增加節點
        try {
            if (!ZkUtil.checkExist(path)) {
                ZkUtil.addNode(parent, child, "chy");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void testTreeCacheListener(){
        ZkUtil.initialize();
        String parent = "/zkconfig";
        String child = "chynode";
        String path = parent + "/" + child;

        MyTreeCacheListener treeCacheListener = new MyTreeCacheListener();

        // 0 只監聽 /zkconfig
        //ZkUtil.registerTreeCacheListener(parent, 0, treeCacheListener);

        // 1 監聽 /zkconfig 和 下一級節點
        ZkUtil.registerTreeCacheListener(parent, 1, treeCacheListener);

        //如果不存在節點增加節點
        try {
            if (!ZkUtil.checkExist(path)) {
                ZkUtil.addNode(parent, child, "chy");
            }

            if (ZkUtil.checkExist(parent)) {
                ZkUtil.updateNodeData(parent, "root");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 

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