9.Dubbo服务订阅源码阅读 - 图1

    ReferenceConfig.java

    1. public synchronized T get() {
    2. // 检测更新<dubbo:reference/>及其子标签
    3. checkAndUpdateSubConfigs();
    4. if (destroyed) {
    5. throw new IllegalStateException("The invoker of ReferenceConfig(" + url + ") has already destroyed!");
    6. }
    7. // ref就是代理对象
    8. if (ref == null) {
    9. // 创建并初始化代理对象
    10. init();
    11. }
    12. return ref;
    13. }
    14. private void init() {
    15. // 若代理对象创建并初始化完毕,则直接结束
    16. if (initialized) {
    17. return;
    18. }
    19. checkStubAndLocal(interfaceClass);
    20. checkMock(interfaceClass);
    21. // 收集消费者元数据
    22. Map<String, String> map = new HashMap<String, String>();
    23. map.put(SIDE_KEY, CONSUMER_SIDE);
    24. appendRuntimeParameters(map);
    25. if (!isGeneric()) {
    26. String revision = Version.getVersion(interfaceClass, version);
    27. if (revision != null && revision.length() > 0) {
    28. map.put(REVISION_KEY, revision);
    29. }
    30. String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames();
    31. if (methods.length == 0) {
    32. logger.warn("No method found in service interface " + interfaceClass.getName());
    33. map.put(METHODS_KEY, ANY_VALUE);
    34. } else {
    35. map.put(METHODS_KEY, StringUtils.join(new HashSet<String>(Arrays.asList(methods)), COMMA_SEPARATOR));
    36. }
    37. }
    38. map.put(INTERFACE_KEY, interfaceName);
    39. appendParameters(map, metrics);
    40. appendParameters(map, application);
    41. appendParameters(map, module);
    42. // remove 'default.' prefix for configs from ConsumerConfig
    43. // appendParameters(map, consumer, Constants.DEFAULT_KEY);
    44. appendParameters(map, consumer);
    45. appendParameters(map, this);
    46. Map<String, Object> attributes = null;
    47. if (CollectionUtils.isNotEmpty(methods)) {
    48. attributes = new HashMap<String, Object>();
    49. for (MethodConfig methodConfig : methods) {
    50. appendParameters(map, methodConfig, methodConfig.getName());
    51. String retryKey = methodConfig.getName() + ".retry";
    52. if (map.containsKey(retryKey)) {
    53. String retryValue = map.remove(retryKey);
    54. if ("false".equals(retryValue)) {
    55. map.put(methodConfig.getName() + ".retries", "0");
    56. }
    57. }
    58. attributes.put(methodConfig.getName(), convertMethodConfig2AyncInfo(methodConfig));
    59. }
    60. }
    61. String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY);
    62. if (StringUtils.isEmpty(hostToRegistry)) {
    63. hostToRegistry = NetUtils.getLocalHost();
    64. } else if (isInvalidLocalHost(hostToRegistry)) {
    65. throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry);
    66. }
    67. map.put(REGISTER_IP_KEY, hostToRegistry);
    68. // ------------------ 以上代码都是在初始化map ---------------
    69. // 创建并初始化消费者代理对象
    70. ref = createProxy(map);
    71. String serviceKey = URL.buildKey(interfaceName, group, version);
    72. ApplicationModel.initConsumerModel(serviceKey, buildConsumerModel(serviceKey, attributes));
    73. // 修改初始化状态变量
    74. initialized = true;
    75. }
    76. //创建代理对象
    77. private T createProxy(Map<String, String> map) {
    78. if (shouldJvmRefer(map)) { // 处理本地调用
    79. URL url = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(map);
    80. invoker = REF_PROTOCOL.refer(interfaceClass, url);
    81. if (logger.isInfoEnabled()) {
    82. logger.info("Using injvm service " + interfaceClass.getName());
    83. }
    84. } else { // 处理远程调用
    85. urls.clear(); // reference retry init will add url to urls, lead to OOM
    86. // 处理直连式的远程调用(即没有注册中心)
    87. if (url != null && url.length() > 0) { // user specified URL, could be peer-to-peer address, or register center's address.
    88. String[] us = SEMICOLON_SPLIT_PATTERN.split(url);
    89. if (us != null && us.length > 0) {
    90. for (String u : us) {
    91. URL url = URL.valueOf(u);
    92. if (StringUtils.isEmpty(url.getPath())) {
    93. url = url.setPath(interfaceName);
    94. }
    95. if (REGISTRY_PROTOCOL.equals(url.getProtocol())) {
    96. urls.add(url.addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map)));
    97. } else {
    98. urls.add(ClusterUtils.mergeUrl(url, map));
    99. }
    100. }
    101. }
    102. } else { // assemble URL from register center's configuration
    103. // 处理具有注册中心的远程调用
    104. // if protocols not injvm checkRegistry
    105. // 若不是本地调用
    106. if (!LOCAL_PROTOCOL.equalsIgnoreCase(getProtocol())){
    107. // 检测所有注册中心的可用性
    108. checkRegistry();
    109. // 获取到所有注册中心的标准化URL
    110. List<URL> us = loadRegistries(false);
    111. if (CollectionUtils.isNotEmpty(us)) {
    112. // 遍历所有注册中心url
    113. for (URL u : us) {
    114. URL monitorUrl = loadMonitor(u);
    115. if (monitorUrl != null) {
    116. map.put(MONITOR_KEY, URL.encode(monitorUrl.toFullString()));
    117. }
    118. // add()中的参数是一个url,该url中包含注册中心url与消费者url
    119. urls.add(u.addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map)));
    120. }
    121. }
    122. if (urls.isEmpty()) {
    123. throw new IllegalStateException("No such any registry to reference " + interfaceName + " on the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion() + ", please config <dubbo:registry address=\"...\" /> to your spring config.");
    124. }
    125. }
    126. }
    127. if (urls.size() == 1) { // 处理只有一个注册中心的情况
    128. // 将这个注册中心中的所有invoker抽象为一个具有容错与降级功能的invoker
    129. invoker = REF_PROTOCOL.refer(interfaceClass, urls.get(0));
    130. } else { // 处理有多个注册中心的情况
    131. List<Invoker<?>> invokers = new ArrayList<Invoker<?>>();
    132. URL registryURL = null;
    133. // 遍历所有注册中心url
    134. for (URL url : urls) {
    135. // 将当前遍历的注册中心中的所有invoker抽象为一个具有容错与降级功能的invoker后,
    136. // 添加到invokers列表中
    137. invokers.add(REF_PROTOCOL.refer(interfaceClass, url));
    138. // 记录最后一个注册中心的url,因为我们在后面要使用该url中所包含的消费者url,
    139. // 所有当前遍历的url中所包含的消费者url都是相同的。故,获取一个即可
    140. if (REGISTRY_PROTOCOL.equals(url.getProtocol())) {
    141. registryURL = url; // use last registry url
    142. }
    143. }
    144. // 若具有可用的注册中心
    145. if (registryURL != null) { // registry url is available
    146. // use RegistryAwareCluster only when register's CLUSTER is available
    147. URL u = registryURL.addParameter(CLUSTER_KEY, RegistryAwareCluster.NAME);
    148. // The invoker wrap relation would be: RegistryAwareClusterInvoker(StaticDirectory) -> FailoverClusterInvoker(RegistryDirectory, will execute route) -> Invoker
    149. // 将所有注册中心抽象出的invoker再次抽象为一个具有容错与降级功能的invoker
    150. // 由于注册中心的数量是不会变化的,所以这里创建的Directory为静态Directory
    151. // 从列表中拿出第一个invoker
    152. invoker = CLUSTER.join(new StaticDirectory(u, invokers));
    153. } else { // not a registry url, must be direct invoke.
    154. invoker = CLUSTER.join(new StaticDirectory(invokers));
    155. }
    156. }
    157. }
    158. if (shouldCheck() && !invoker.isAvailable()) {
    159. throw new IllegalStateException("Failed to check the status of the service " + interfaceName + ". No provider available for the service " + (group == null ? "" : group + "/") + interfaceName + (version == null ? "" : ":" + version) + " from the url " + invoker.getUrl() + " to the consumer " + NetUtils.getLocalHost() + " use dubbo version " + Version.getVersion());
    160. }
    161. if (logger.isInfoEnabled()) {
    162. logger.info("Refer dubbo service " + interfaceClass.getName() + " from url " + invoker.getUrl());
    163. }
    164. /**
    165. * @since 2.7.0
    166. * ServiceData Store
    167. */
    168. // 将消费者元数据写入到元数据中心
    169. MetadataReportService metadataReportService = null;
    170. if ((metadataReportService = getMetadataReportService()) != null) {
    171. URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map);
    172. metadataReportService.publishConsumer(consumerURL);
    173. }
    174. // create service proxy 创建消费者代理对象
    175. return (T) PROXY_FACTORY.getProxy(invoker);
    176. }

    (T) PROXY_FACTORY.getProxy(invoker);还是会生成一个Adaptive自适应类,上一章源码阅读中,我们已经把该类的源代码复制出来了,如下:

    1. package org.apache.dubbo.rpc;
    2. import org.apache.dubbo.common.extension.ExtensionLoader;
    3. public class ProxyFactory$Adaptive implements org.apache.dubbo.rpc.ProxyFactory {
    4. public org.apache.dubbo.rpc.Invoker getInvoker(java.lang.Object arg0, java.lang.Class arg1, org.apache.dubbo.common.URL arg2) throws org.apache.dubbo.rpc.RpcException {
    5. if (arg2 == null) throw new IllegalArgumentException("url == null");
    6. org.apache.dubbo.common.URL url = arg2;
    7. // 可以看到这里使用javassist来进行动态代理
    8. String extName = url.getParameter("proxy", "javassist");
    9. if (extName == null)
    10. throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.ProxyFactory) name from url (" + url.toString() + ") use keys([proxy])");
    11. org.apache.dubbo.rpc.ProxyFactory extension = (org.apache.dubbo.rpc.ProxyFactory) ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.ProxyFactory.class).getExtension(extName);
    12. // 使用javassit创建的代理对象
    13. // StubProxyFactoryWrapper.java -> getInvoker
    14. return extension.getInvoker(arg0, arg1, arg2);
    15. }
    16. public java.lang.Object getProxy(org.apache.dubbo.rpc.Invoker arg0, boolean arg1) throws org.apache.dubbo.rpc.RpcException {
    17. if (arg0 == null) throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument == null");
    18. if (arg0.getUrl() == null)
    19. throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument getUrl() == null");
    20. org.apache.dubbo.common.URL url = arg0.getUrl();
    21. String extName = url.getParameter("proxy", "javassist");
    22. if (extName == null)
    23. throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.ProxyFactory) name from url (" + url.toString() + ") use keys([proxy])");
    24. org.apache.dubbo.rpc.ProxyFactory extension = (org.apache.dubbo.rpc.ProxyFactory) ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.ProxyFactory.class).getExtension(extName);
    25. return extension.getProxy(arg0, arg1);
    26. }
    27. public java.lang.Object getProxy(org.apache.dubbo.rpc.Invoker arg0) throws org.apache.dubbo.rpc.RpcException {
    28. if (arg0 == null) throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument == null");
    29. if (arg0.getUrl() == null)
    30. throw new IllegalArgumentException("org.apache.dubbo.rpc.Invoker argument getUrl() == null");
    31. org.apache.dubbo.common.URL url = arg0.getUrl();
    32. String extName = url.getParameter("proxy", "javassist");
    33. if (extName == null)
    34. throw new IllegalStateException("Failed to get extension (org.apache.dubbo.rpc.ProxyFactory) name from url (" + url.toString() + ") use keys([proxy])");
    35. org.apache.dubbo.rpc.ProxyFactory extension = (org.apache.dubbo.rpc.ProxyFactory) ExtensionLoader.getExtensionLoader(org.apache.dubbo.rpc.ProxyFactory.class).getExtension(extName);
    36. return extension.getProxy(arg0);
    37. }
    38. }

    JavassistProxyFactory.java

    1. public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
    2. // 为指定接口创建代理对象并调用带参构造器
    3. return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker));
    4. }

    InvokerInvocationHandler.java

    1. public InvokerInvocationHandler(Invoker<?> handler) {
    2. this.invoker = handler;
    3. }
    4. @Override
    5. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    6. // 获取到RPC远程调用的方法名
    7. String methodName = method.getName();
    8. Class<?>[] parameterTypes = method.getParameterTypes();
    9. // 若当前方法为Object的方法,则为本地方法调用
    10. if (method.getDeclaringClass() == Object.class) {
    11. return method.invoke(invoker, args);
    12. }
    13. if ("toString".equals(methodName) && parameterTypes.length == 0) {
    14. return invoker.toString();
    15. }
    16. if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
    17. return invoker.hashCode();
    18. }
    19. if ("equals".equals(methodName) && parameterTypes.length == 1) {
    20. return invoker.equals(args[0]);
    21. }
    22. // 远程调用
    23. return invoker.invoke(new RpcInvocation(method, args)).recreate();
    24. }

    核心代理调用类触发点找到了,接下来我们先回去ReferenceConfig.java中深跟一下还没跟踪的方法。它们在 init()-》createProxy()-》shouldJvmRefer() -》shouldJvmRefer() -》isInjvmRefer() 如下:

    InjvmProtocol.java

    1. //根据标签生产URL信息中再判断到时是本地调用还是远程调用
    2. public boolean isInjvmRefer(URL url) {
    3. // 获取<dubbo:reference/>的scope属性
    4. String scope = url.getParameter(SCOPE_KEY);
    5. // 若scope为local或injvm属性为true,则为本地调用
    6. if (SCOPE_LOCAL.equals(scope) || (url.getParameter(LOCAL_PROTOCOL, false))) {
    7. // if it's declared as local reference
    8. // 'scope=local' is equivalent to 'injvm=true', injvm will be deprecated in the future release
    9. return true;
    10. // 若scope为remote 则是远程调用
    11. } else if (SCOPE_REMOTE.equals(scope)) {
    12. // it's declared as remote reference
    13. return false;
    14. // 是泛化服务, 则也是远程调用
    15. } else if (url.getParameter(GENERIC_KEY, false)) {
    16. // generic invocation is not local reference
    17. return false;
    18. // 从缓存中拿, 如果有。则说明是本地调用。因为Map是本地缓存
    19. } else if (getExporter(exporterMap, url) != null) {
    20. // by default, go through local reference if there's the service exposed locally
    21. return true;
    22. } else {
    23. return false;
    24. }
    25. }

    9.Dubbo服务订阅源码阅读 - 图2

    RegistryProtocol.java

    1. public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
    2. url = URLBuilder.from(url)
    3. .setProtocol(url.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY))
    4. .removeParameter(REGISTRY_KEY)
    5. .build();
    6. // 获取注册对象
    7. Registry registry = registryFactory.getRegistry(url);
    8. // 当前是否是注册中心类型
    9. if (RegistryService.class.equals(type)) {
    10. return proxyFactory.getInvoker((T) registry, type, url);
    11. }
    12. // group="a,b" or group="*"
    13. Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY));
    14. String group = qs.get(GROUP_KEY);
    15. if (group != null && group.length() > 0) {
    16. if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) {
    17. return doRefer(getMergeableCluster(), registry, type, url);
    18. }
    19. }
    20. return doRefer(cluster, registry, type, url);
    21. }
    22. private <T> Invoker<T> doRefer(Cluster cluster, Registry registry, Class<T> type, URL url) {
    23. // 创建一个动态Directory
    24. RegistryDirectory<T> directory = new RegistryDirectory<T>(type, url);
    25. directory.setRegistry(registry);
    26. directory.setProtocol(protocol);
    27. // all attributes of REFER_KEY
    28. Map<String, String> parameters = new HashMap<String, String>(directory.getUrl().getParameters());
    29. URL subscribeUrl = new URL(CONSUMER_PROTOCOL, parameters.remove(REGISTER_IP_KEY), 0, type.getName(), parameters);
    30. if (!ANY_VALUE.equals(url.getServiceInterface()) && url.getParameter(REGISTER_KEY, true)) {
    31. directory.setRegisteredConsumerUrl(getRegisteredConsumerUrl(subscribeUrl, url));
    32. // 将consumer注册到zk
    33. registry.register(directory.getRegisteredConsumerUrl());
    34. }
    35. // 获取到RouterFactory的所有激活类创建的router实例,添加到directory中
    36. directory.buildRouterChain(subscribeUrl);
    37. // 服务订阅(为三个分类节点添加watcher监听,并获取当前zk中三个分类节点下的所有子节点url)
    38. /**
    39. * 订阅zk注册中心的节点变更。订阅的节点为:
    40. * 1.providers
    41. * 2.configurators
    42. * 3.routers
    43. **/
    44. directory.subscribe(subscribeUrl.addParameter(CATEGORY_KEY,
    45. PROVIDERS_CATEGORY + "," + CONFIGURATORS_CATEGORY + "," + ROUTERS_CATEGORY));
    46. // 将动态列表directory中invoker列表抽象(创建)出一个具有容错与降级功能的invoker
    47. Invoker invoker = cluster.join(directory);
    48. ProviderConsumerRegTable.registerConsumer(invoker, url, subscribeUrl, directory);
    49. return invoker;
    50. }

    RegistryDirectory.java

    1. public void subscribe(URL url) {
    2. setConsumerUrl(url);
    3. CONSUMER_CONFIGURATION_LISTENER.addNotifyListener(this);
    4. serviceConfigurationListener = new ReferenceConfigurationListener(this, url);
    5. registry.subscribe(url, this); //
    6. }

    FailbackRegistry.java

    1. public void subscribe(URL url, NotifyListener listener) {
    2. super.subscribe(url, listener);
    3. removeFailedSubscribed(url, listener);
    4. try {
    5. // Sending a subscription request to the server side
    6. doSubscribe(url, listener); // 发送订阅请求到zk
    7. } catch (Exception e) {
    8. Throwable t = e;
    9. List<URL> urls = getCacheUrls(url);
    10. if (CollectionUtils.isNotEmpty(urls)) {
    11. notify(url, listener, urls);
    12. logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t);
    13. } else {
    14. // If the startup detection is opened, the Exception is thrown directly.
    15. boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
    16. && url.getParameter(Constants.CHECK_KEY, true);
    17. boolean skipFailback = t instanceof SkipFailbackWrapperException;
    18. if (check || skipFailback) {
    19. if (skipFailback) {
    20. t = t.getCause();
    21. }
    22. throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t);
    23. } else {
    24. logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
    25. }
    26. }
    27. // Record a failed registration request to a failed list, retry regularly
    28. addFailedSubscribed(url, listener);
    29. }
    30. }

    ZookeeperRegistry.java

    1. public void doSubscribe(final URL url, final NotifyListener listener) {
    2. try {
    3. if (ANY_VALUE.equals(url.getServiceInterface())) { // 处理interface属性值设置的为*的情况
    4. String root = toRootPath();
    5. ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
    6. if (listeners == null) {
    7. zkListeners.putIfAbsent(url, new ConcurrentHashMap<>());
    8. listeners = zkListeners.get(url);
    9. }
    10. ChildListener zkListener = listeners.get(listener);
    11. if (zkListener == null) {
    12. listeners.putIfAbsent(listener, (parentPath, currentChilds) -> {
    13. for (String child : currentChilds) {
    14. child = URL.decode(child);
    15. if (!anyServices.contains(child)) {
    16. anyServices.add(child);
    17. subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child,
    18. Constants.CHECK_KEY, String.valueOf(false)), listener);
    19. }
    20. }
    21. });
    22. zkListener = listeners.get(listener);
    23. }
    24. zkClient.create(root, false);
    25. List<String> services = zkClient.addChildListener(root, zkListener);
    26. if (CollectionUtils.isNotEmpty(services)) {
    27. for (String service : services) {
    28. service = URL.decode(service);
    29. anyServices.add(service);
    30. subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service,
    31. Constants.CHECK_KEY, String.valueOf(false)), listener);
    32. }
    33. }
    34. } else { // 理interface属性值为普通接口的情况
    35. // 该urls列表中将来会存放所有分类节点下的所有子节点
    36. List<URL> urls = new ArrayList<>();
    37. // 遍历所有分类节点
    38. for (String path : toCategoriesPath(url)) {
    39. ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.get(url);
    40. if (listeners == null) {
    41. zkListeners.putIfAbsent(url, new ConcurrentHashMap<>());
    42. listeners = zkListeners.get(url);
    43. }
    44. ChildListener zkListener = listeners.get(listener);
    45. if (zkListener == null) {
    46. listeners.putIfAbsent(listener, (parentPath, currentChilds) -> ZookeeperRegistry.this.notify(url, listener, toUrlsWithEmpty(url, parentPath, currentChilds)));
    47. zkListener = listeners.get(listener);
    48. }
    49. // 创建当前分类节点(持久节点)
    50. zkClient.create(path, false);
    51. // 为当前分类节点添加“子节点列表变更的”watcher监听
    52. // 返回值为当前分类节点的所有子节点列表
    53. List<String> children = zkClient.addChildListener(path, zkListener);
    54. if (children != null) {
    55. urls.addAll(toUrlsWithEmpty(url, path, children));
    56. }
    57. }
    58. // 主动调用各个分类节点的监听器,将zk中的数据更新到本地
    59. notify(url, listener, urls);
    60. }
    61. } catch (Throwable e) {
    62. throw new RpcException("Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
    63. }
    64. }

    FailbackRegistry.java

    1. protected void notify(URL url, NotifyListener listener, List<URL> urls) {
    2. if (url == null) {
    3. throw new IllegalArgumentException("notify url == null");
    4. }
    5. if (listener == null) {
    6. throw new IllegalArgumentException("notify listener == null");
    7. }
    8. try {
    9. doNotify(url, listener, urls); //准备跟踪
    10. } catch (Exception t) {
    11. // Record a failed registration request to a failed list, retry regularly
    12. addFailedNotified(url, listener, urls);
    13. logger.error("Failed to notify for subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
    14. }
    15. }
    16. protected void doNotify(URL url, NotifyListener listener, List<URL> urls) {
    17. super.notify(url, listener, urls);
    18. }

    AbstractRegistry.java

    1. protected void notify(URL url, NotifyListener listener, List<URL> urls) {
    2. if (url == null) {
    3. throw new IllegalArgumentException("notify url == null");
    4. }
    5. if (listener == null) {
    6. throw new IllegalArgumentException("notify listener == null");
    7. }
    8. if ((CollectionUtils.isEmpty(urls))
    9. && !ANY_VALUE.equals(url.getServiceInterface())) {
    10. logger.warn("Ignore empty notify urls for subscribe url " + url);
    11. return;
    12. }
    13. if (logger.isInfoEnabled()) {
    14. logger.info("Notify urls for subscribe url " + url + ", urls: " + urls);
    15. }
    16. // keep every provider's category.
    17. Map<String, List<URL>> result = new HashMap<>();
    18. for (URL u : urls) {
    19. if (UrlUtils.isMatch(url, u)) {
    20. String category = u.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
    21. List<URL> categoryList = result.computeIfAbsent(category, k -> new ArrayList<>());
    22. categoryList.add(u);
    23. }
    24. }
    25. if (result.size() == 0) {
    26. return;
    27. }
    28. Map<String, List<URL>> categoryNotified = notified.computeIfAbsent(url, u -> new ConcurrentHashMap<>());
    29. for (Map.Entry<String, List<URL>> entry : result.entrySet()) {
    30. String category = entry.getKey();
    31. List<URL> categoryList = entry.getValue();
    32. categoryNotified.put(category, categoryList);
    33. listener.notify(categoryList); // 调用分类节点的监听
    34. // We will update our cache file after each notification.
    35. // When our Registry has a subscribe failure due to network jitter, we can return at least the existing cache URL.
    36. saveProperties(url);
    37. }
    38. }

    RegistryDirectory.java

    1. public synchronized void notify(List<URL> urls) {
    2. Map<String, List<URL>> categoryUrls = urls.stream()
    3. .filter(Objects::nonNull)
    4. .filter(this::isValidCategory)
    5. .filter(this::isNotCompatibleFor26x)
    6. .collect(Collectors.groupingBy(url -> {
    7. if (UrlUtils.isConfigurator(url)) {
    8. return CONFIGURATORS_CATEGORY;
    9. } else if (UrlUtils.isRoute(url)) {
    10. return ROUTERS_CATEGORY;
    11. } else if (UrlUtils.isProvider(url)) {
    12. return PROVIDERS_CATEGORY;
    13. }
    14. return "";
    15. }));
    16. // 处理configurators分类节点情况
    17. List<URL> configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList());
    18. this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators);
    19. // 处理routers分类节点情况
    20. List<URL> routerURLs = categoryUrls.getOrDefault(ROUTERS_CATEGORY, Collections.emptyList());
    21. toRouters(routerURLs) // 返回Optional
    22. // 若Optional中封装的对象不空,则调用Lambda的实例方法引用addRouters(),即将这个路由添加到directory
    23. .ifPresent(this::addRouters);
    24. // providers
    25. // 处理providers分类节点情况
    26. List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList());
    27. // 从zk中获取最新的提供者更新到directory
    28. refreshOverrideAndInvoker(providerURLs);
    29. }
    30. private Optional<List<Router>> toRouters(List<URL> urls) {
    31. if (urls == null || urls.isEmpty()) {
    32. return Optional.empty();
    33. }
    34. List<Router> routers = new ArrayList<>();
    35. for (URL url : urls) {
    36. // 若当前url以empty作为protocol,则说明其不是一个有效url
    37. if (EMPTY_PROTOCOL.equals(url.getProtocol())) {
    38. continue;
    39. }
    40. // 获取到url中的router属性值,当前值为condition,表示这是一个条件路由
    41. String routerType = url.getParameter(ROUTER_KEY);
    42. if (routerType != null && routerType.length() > 0) {
    43. // 将路由类型作为url的protocol,即当前的url变为了condition://...
    44. url = url.setProtocol(routerType);
    45. }
    46. try {
    47. // 创建路由
    48. Router router = ROUTER_FACTORY.getRouter(url);
    49. // 将该路由实例记录下来
    50. if (!routers.contains(router)) {
    51. routers.add(router);
    52. }
    53. } catch (Throwable t) {
    54. logger.error("convert router url to router error, url: " + url, t);
    55. }
    56. }
    57. return Optional.of(routers);
    58. }
    59. private void refreshOverrideAndInvoker(List<URL> urls) {
    60. // mock zookeeper://xxx?mock=return null
    61. overrideDirectoryUrl();
    62. refreshInvoker(urls); //
    63. }
    64. private void refreshInvoker(List<URL> invokerUrls) {
    65. Assert.notNull(invokerUrls, "invokerUrls should not be null");
    66. if (invokerUrls.size() == 1
    67. && invokerUrls.get(0) != null
    68. && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
    69. this.forbidden = true; // Forbid to access 禁止远程调用
    70. this.invokers = Collections.emptyList();
    71. routerChain.setInvokers(this.invokers);
    72. destroyAllInvokers(); // Close all invokers 销毁缓存中的所有invoker
    73. } else { // 处理远程调用的情况
    74. this.forbidden = false; // Allow to access
    75. Map<String, Invoker<T>> oldUrlInvokerMap = this.urlInvokerMap; // local reference
    76. if (invokerUrls == Collections.<URL>emptyList()) {
    77. invokerUrls = new ArrayList<>();
    78. }
    79. if (invokerUrls.isEmpty() && this.cachedInvokerUrls != null) {
    80. invokerUrls.addAll(this.cachedInvokerUrls);
    81. } else {
    82. this.cachedInvokerUrls = new HashSet<>();
    83. this.cachedInvokerUrls.addAll(invokerUrls);//Cached invoker urls, convenient for comparison
    84. }
    85. if (invokerUrls.isEmpty()) {
    86. return;
    87. }
    88. // 获取到最新的invoker,key为zk中的节点名称,即url,value为该url对应的invoker
    89. Map<String, Invoker<T>> newUrlInvokerMap = toInvokers(invokerUrls);// Translate url list to Invoker map
    90. /**
    91. * If the calculation is wrong, it is not processed.
    92. *
    93. * 1. The protocol configured by the client is inconsistent with the protocol of the server.
    94. * eg: consumer protocol = dubbo, provider only has other protocol services(rest).
    95. * 2. The registration center is not robust and pushes illegal specification data.
    96. *
    97. */
    98. if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
    99. logger.error(new IllegalStateException("urls to invokers error .invokerUrls.size :" + invokerUrls.size() + ", invoker.size :0. urls :" + invokerUrls
    100. .toString()));
    101. return;
    102. }
    103. // 从map中获取所有最新的invoker
    104. List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values()));
    105. // pre-route and build cache, notice that route cache should build on original Invoker list.
    106. // toMergeMethodInvokerMap() will wrap some invokers having different groups, those wrapped invokers not should be routed.
    107. // 将所有当前可用的invoker写入到routerChain,即写入到了directory中
    108. // 后面进行服务路由时,就是在这一堆invoker中进行路由
    109. routerChain.setInvokers(newInvokers);
    110. this.invokers = multiGroup ? toMergeInvokerList(newInvokers) : newInvokers;
    111. this.urlInvokerMap = newUrlInvokerMap;
    112. try {
    113. // 销毁所有不可用的invoker
    114. destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker
    115. } catch (Exception e) {
    116. logger.warn("destroyUnusedInvokers error. ", e);
    117. }
    118. }
    119. }
    120. private void destroyAllInvokers() {
    121. // 获取缓存中的invoker
    122. Map<String, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap; // local reference
    123. if (localUrlInvokerMap != null) {
    124. // 遍历缓存中的所有invoker
    125. for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) {
    126. try {
    127. // 销毁当前遍历invoker
    128. invoker.destroy();
    129. } catch (Throwable t) {
    130. logger.warn("Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(), t);
    131. }
    132. }
    133. localUrlInvokerMap.clear();
    134. }
    135. invokers = null;
    136. }
    137. private void destroyUnusedInvokers(Map<String, Invoker<T>> oldUrlInvokerMap, Map<String, Invoker<T>> newUrlInvokerMap) {
    138. // 若存放最新的invoker的map为空,则意味着没有可用的invoker,
    139. // 则将缓存中的所有invoker全部销毁
    140. if (newUrlInvokerMap == null || newUrlInvokerMap.size() == 0) {
    141. // 销毁缓存中的所有invoker
    142. destroyAllInvokers();
    143. return;
    144. }
    145. // check deleted invoker
    146. List<String> deleted = null;
    147. if (oldUrlInvokerMap != null) {
    148. Collection<Invoker<T>> newInvokers = newUrlInvokerMap.values();
    149. // 遍历缓存中的所有invoker
    150. for (Map.Entry<String, Invoker<T>> entry : oldUrlInvokerMap.entrySet()) {
    151. // 若最新的invoker中不包含当前遍历的invoker,
    152. // 则说明这个遍历的invoker主机已经挂了,可以销毁了(将其放入到一个销毁列表中)
    153. if (!newInvokers.contains(entry.getValue())) {
    154. if (deleted == null) {
    155. deleted = new ArrayList<>();
    156. }
    157. deleted.add(entry.getKey());
    158. }
    159. }
    160. }
    161. // 如果存在挂了的主机将逐个进行销毁
    162. if (deleted != null) {
    163. // 销毁deleted列表中的所有invoker
    164. for (String url : deleted) {
    165. if (url != null) {
    166. Invoker<T> invoker = oldUrlInvokerMap.remove(url);
    167. if (invoker != null) {
    168. try {
    169. invoker.destroy();
    170. if (logger.isDebugEnabled()) {
    171. logger.debug("destroy invoker[" + invoker.getUrl() + "] success. ");
    172. }
    173. } catch (Exception e) {
    174. logger.warn("destroy invoker[" + invoker.getUrl() + "] failed. " + e.getMessage(), e);
    175. }
    176. }
    177. }
    178. }
    179. }
    180. }