motan源碼解讀:註冊中心zookeeper(2)

      上文大概講解了利用zookeeper如何實現註冊中心的。本文主要是從源碼角度說明下。代碼都在模塊motan-registry-zookeeper中,其實在在這個模塊中就3個類。html

  •    ZkNodeType: 跟上文的圖中的節點類型是對應的
enum ZkNodeType {
    AVAILABLE_SERVER,
    UNAVAILABLE_SERVER,
    CLIENT
}
  • ZookeeperRegistryFactory:顧名思義
  • zookeeper註冊中心的註冊工廠ZookeeperRegistry

   最重要的就是建立節點node

@Override
    protected void doRegister(URL url) {
        try {
            // 防止舊節點未正常註銷
            removeNode(url, ZkNodeType.AVAILABLE_SERVER);
            removeNode(url, ZkNodeType.UNAVAILABLE_SERVER);
            createNode(url, ZkNodeType.UNAVAILABLE_SERVER);
        } catch (Throwable e) {
            throw new MotanFrameworkException(String.format("Failed to register %s to zookeeper(%s), cause: %s", url, getUrl(), e.getMessage()));
        }
    }

    還有client對server列表的監聽:註釋不少,本身看。ide

 @Override
    protected void doSubscribe(final URL url, final NotifyListener notifyListener) {
        try {
            ConcurrentHashMap<NotifyListener, IZkChildListener> childChangeListeners = urlListeners.get(url);
            if (childChangeListeners == null) {
                urlListeners.putIfAbsent(url, new ConcurrentHashMap<NotifyListener, IZkChildListener>());
                childChangeListeners = urlListeners.get(url);
            }
            IZkChildListener zkChildListener = childChangeListeners.get(notifyListener);
            if (zkChildListener == null) {
                childChangeListeners.putIfAbsent(notifyListener, new IZkChildListener() {
                    @Override
                    public void handleChildChange(String parentPath, List<String> currentChilds) {
                        ZookeeperRegistry.this.notify(url, notifyListener, nodeChildsToUrls(parentPath, currentChilds));
                        LoggerUtil.info(String.format("[ZookeeperRegistry] service list change: path=%s, currentChilds=%s", parentPath, currentChilds.toString()));
                    }
                });
                zkChildListener = childChangeListeners.get(notifyListener);
            }

            // 防止舊節點未正常註銷
            removeNode(url, ZkNodeType.CLIENT);
            createNode(url, ZkNodeType.CLIENT);

            // 訂閱server節點,並獲取當前可用server
            String serverTypePath = toNodeTypePath(url, ZkNodeType.AVAILABLE_SERVER);
            List<String> currentChilds = zkClient.subscribeChildChanges(serverTypePath, zkChildListener);
            LoggerUtil.info(String.format("[ZookeeperRegistry] subscribe: path=%s, info=%s", toNodePath(url, ZkNodeType.AVAILABLE_SERVER), url.toFullStr()));
            notify(url, notifyListener, nodeChildsToUrls(serverTypePath, currentChilds));
        } catch (Throwable e) {
            throw new MotanFrameworkException(String.format("Failed to subscribe %s to zookeeper(%s), cause: %s", url, getUrl(), e.getMessage()));
        }
    }

 http://www.cnblogs.com/scott19820130/p/4940066.htmlthis

相關文章
相關標籤/搜索