motan源码解读:注册中心zookeeper(2)
上文大概讲解了利用zookeeper如何实现注册中心的。本文主要是从源码角度说明下。代码都在模块motan-registry-zookeeper中,其实在在这个模块中就3个类。
-
ZkNodeType: 跟上文的图中的节点类型是对应的
enum ZkNodeType { AVAILABLE_SERVER, UNAVAILABLE_SERVER, CLIENT }
-
ZookeeperRegistryFactory:顾名思义
-
zookeeper注册中心的注册工厂ZookeeperRegistry
最重要的就是创建节点
@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列表的监听:注释很多,自己看。
@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.html