org.apache.dubbo 2.7.7 服务消费源码

org.apache.dubbo 服务消费原理源码分析:

  本文主要针对 dubbo-spring-boot-starter   2.7.7版本, 对应的 org.apache.dubbo 2.7.7 版本的源码。

  本文主要从以下几个点来分析:

  1. 服务消费的入口。
  2. 构建远程服务的代理。
  3. RegistryDirectory 目录服务获取目标服务的url地址。
  4. 客户端服务通信的建立。
  5. 接口调用流程。

服务消费的入口:

  Dubbo 提供了一个自动配置类 DubboAutoConfiguration,其中除了会自动注入服务端的注解处理器 ServiceAnnotationBeanPostProcessor 之外,还会创建一个客户端的注解处理器 ReferenceAnnotationBeanPostProcessor。

  ReferenceAnnotationBeanPostProcessor 重写了 doGetInjectedBean 方法,在依赖注入的时候会调用该方法进行依赖注入,而我们知道。在使用@DubboReference 的时候,这个类一定是个动态代理对象。我们先来看一下这个代码:

@Override
protected Object doGetInjectedBean(AnnotationAttributes attributes, Object bean, String beanName, Class<?> injectedType,
                                       InjectionMetadata.InjectedElement injectedElement) throws Exception {
        /**
         * The name of bean that annotated Dubbo's {@link Service @Service} in local Spring {@link ApplicationContext}
         */
        String referencedBeanName = buildReferencedBeanName(attributes, injectedType);

        /**
         * The name of bean that is declared by {@link Reference @Reference} annotation injection
         */
        String referenceBeanName = getReferenceBeanName(attributes, injectedType);

        ReferenceBean referenceBean = buildReferenceBeanIfAbsent(referenceBeanName, attributes, injectedType);

        boolean localServiceBean = isLocalServiceBean(referencedBeanName, referenceBean, attributes);
     // 注册一个ReferenceBean到Spring IOC容器中
        registerReferenceBean(referencedBeanName, referenceBean, attributes, localServiceBean, injectedType);

        cacheInjectedReferenceBean(referenceBean, injectedElement);
      //调用 getOrCreateProxy 返回一个动态代理对象
        return getOrCreateProxy(referencedBeanName, referenceBean, localServiceBean, injectedType);
}

  最终这里会调用 ReferenceConfig#get 来获取该代理对象:

public synchronized T get() {
        if (destroyed) {
            throw new IllegalStateException("The invoker of ReferenceConfig(" + url + ") has already destroyed!");
        }
        if (ref == null) {
            init();
        }
        return ref;
}

  开始调用init方法进行ref也就是代理对象的初始化动作

  • 检查配置信息
  • 根据dubbo配置,构建map集合。
  • 调用 createProxy 创建动态代理对象
public synchronized void init() {
        if (initialized) {//如果已经初始化,则直接返回
            return;
        }

        if (bootstrap == null) {
            bootstrap = DubboBootstrap.getInstance();
            bootstrap.init();
        }
     //检查配置
        checkAndUpdateSubConfigs();
       //检查本地存根 local与stub
        checkStubAndLocal(interfaceClass);
        ConfigValidationUtils.checkMock(interfaceClass, this);

        Map<String, String> map = new HashMap<String, String>();
        map.put(SIDE_KEY, CONSUMER_SIDE);
     //添加运行时参数
        ReferenceConfigBase.appendRuntimeParameters(map);
        if (!ProtocolUtils.isGeneric(generic)) {//检查是否为泛化接口
           //获取版本信息

            String revision = Version.getVersion(interfaceClass, version);
            if (revision != null && revision.length() > 0) {
                map.put(REVISION_KEY, revision);
            }
        //获取接口方法列表,添加到map中
            String[] methods = Wrapper.getWrapper(interfaceClass).getMethodNames();
            if (methods.length == 0) {
                logger.warn("No method found in service interface " + interfaceClass.getName());
                map.put(METHODS_KEY, ANY_VALUE);
            } else {
                map.put(METHODS_KEY, StringUtils.join(new HashSet<String>(Arrays.asList(methods)), COMMA_SEPARATOR));
            }
        }
     //通过class加载配置信息
        map.put(INTERFACE_KEY, interfaceName);
        AbstractConfig.appendParameters(map, getMetrics());
        AbstractConfig.appendParameters(map, getApplication());
        AbstractConfig.appendParameters(map, getModule());
        // remove 'default.' prefix for configs from ConsumerConfig
        // appendParameters(map, consumer, Constants.DEFAULT_KEY);
        AbstractConfig.appendParameters(map, consumer);
        AbstractConfig.appendParameters(map, this);
     //将元数据配置信息放入到map中
        MetadataReportConfig metadataReportConfig = getMetadataReportConfig();
        if (metadataReportConfig != null && metadataReportConfig.isValid()) {
            map.putIfAbsent(METADATA_KEY, REMOTE_METADATA_STORAGE_TYPE);
        }
       //遍历methodConfig,组装method参数信息
        Map<String, AsyncMethodInfo> attributes = null;
        if (CollectionUtils.isNotEmpty(getMethods())) {
            attributes = new HashMap<>();
            for (MethodConfig methodConfig : getMethods()) {
                AbstractConfig.appendParameters(map, methodConfig, methodConfig.getName());
                String retryKey = methodConfig.getName() + ".retry";
                if (map.containsKey(retryKey)) {
                    String retryValue = map.remove(retryKey);
                    if ("false".equals(retryValue)) {
                        map.put(methodConfig.getName() + ".retries", "0");
                    }
                }
                AsyncMethodInfo asyncMethodInfo = AbstractConfig.convertMethodConfig2AsyncInfo(methodConfig);
                if (asyncMethodInfo != null) {
//                    consumerModel.getMethodModel(methodConfig.getName()).addAttribute(ASYNC_KEY, asyncMethodInfo);
                    attributes.put(methodConfig.getName(), asyncMethodInfo);
                }
            }
        }
     //获取服务消费者ip地址
        String hostToRegistry = ConfigUtils.getSystemProperty(DUBBO_IP_TO_REGISTRY);
        if (StringUtils.isEmpty(hostToRegistry)) {
            hostToRegistry = NetUtils.getLocalHost();
        } else if (isInvalidLocalHost(hostToRegistry)) {
            throw new IllegalArgumentException("Specified invalid registry ip from property:" + DUBBO_IP_TO_REGISTRY + ", value:" + hostToRegistry);
        }
        map.put(REGISTER_IP_KEY, hostToRegistry);

        serviceMetadata.getAttachments().putAll(map);

        ref = createProxy(map);

        serviceMetadata.setTarget(ref);
        serviceMetadata.addAttribute(PROXY_CLASS_REF, ref);
        ConsumerModel consumerModel = repository.lookupReferredService(serviceMetadata.getServiceKey());
        consumerModel.setProxyObject(ref);
        consumerModel.init(attributes);

        initialized = true;

        // dispatch a ReferenceConfigInitializedEvent since 2.7.4
        dispatch(new ReferenceConfigInitializedEvent(this, invoker));
}

  ReferenceConfig#createProxy:首先我们需要注意一个点,这里是创建一个代理对象,而这个代理对象应该也和协议有关系,也就是不同的协议,使用的代理对象也应该不一样

private T createProxy(Map<String, String> map) {
        if (shouldJvmRefer(map)) {
            URL url = new URL(LOCAL_PROTOCOL, LOCALHOST_VALUE, 0, interfaceClass.getName()).addParameters(map);
            invoker = REF_PROTOCOL.refer(interfaceClass, url);
            if (logger.isInfoEnabled()) {
                logger.info("Using injvm service " + interfaceClass.getName());
            }
        } else {
            urls.clear();
        // 我们在注解上配置的uel信息,表示点对点通信方式
            if (url != null && url.length() > 0) { // user specified URL, could be peer-to-peer address, or register center's address.
                String[] us = SEMICOLON_SPLIT_PATTERN.split(url);
                if (us != null && us.length > 0) {
                    for (String u : us) {
                        URL url = URL.valueOf(u);
                        if (StringUtils.isEmpty(url.getPath())) {
                            url = url.setPath(interfaceName);
                        }
                        if (UrlUtils.isRegistry(url)) {
                            urls.add(url.addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map)));
                        } else {
                            urls.add(ClusterUtils.mergeUrl(url, map));
                        }
                    }
                }
            } else { // assemble URL from register center's configuration
                // if protocols not injvm checkRegistry
           //检查协议是否是injvm

                if (!LOCAL_PROTOCOL.equalsIgnoreCase(getProtocol())) {
                    checkRegistry();//检查注册中心配置
            //获取注册中心列表,由于可以配置多个注册中心,所以这里返回所有配置的注册中心信息

                    List<URL> us = ConfigValidationUtils.loadRegistries(this, false);
                    if (CollectionUtils.isNotEmpty(us)) {//遍历注册中心列表,添加到urls中
                        for (URL u : us) {
                            URL monitorUrl = ConfigValidationUtils.loadMonitor(this, u);
                            if (monitorUrl != null) {
                                map.put(MONITOR_KEY, URL.encode(monitorUrl.toFullString()));
                            }
                            urls.add(u.addParameterAndEncoded(REFER_KEY, StringUtils.toQueryString(map)));
                        }
                    }
                    if (urls.isEmpty()) {
                        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.");
                    }
                }
            }
       //如果urls=1,表示只配置了一个注册中心,则直接取一个。
            if (urls.size() == 1) {
                invoker = REF_PROTOCOL.refer(interfaceClass, urls.get(0));
            } else {
         //否则,它会把多个注册中心的协议都分别构建一个invoker。 这就是服务提供者的服务列表
                List<Invoker<?>> invokers = new ArrayList<Invoker<?>>();
                URL registryURL = null;
                for (URL url : urls) {
                    invokers.add(REF_PROTOCOL.refer(interfaceClass, url));
                    if (UrlUtils.isRegistry(url)) {
                        registryURL = url; // use last registry url
                    }
                }
           //如果registryURL不为空
          //则通过CLUSTER.join把invokers以静态的Directory形式构建一个invoker对象。
           //目的是实现注册中心的路由
                if (registryURL != null) { // registry url is available
                    // for multi-subscription scenario, use 'zone-aware' policy by default
                    URL u = registryURL.addParameterIfAbsent(CLUSTER_KEY, ZoneAwareCluster.NAME);
                    // The invoker wrap relation would be like: ZoneAwareClusterInvoker(StaticDirectory) -> FailoverClusterInvoker(RegistryDirectory, routing happens here) -> Invoker
                    invoker = CLUSTER.join(new StaticDirectory(u, invokers));
                } else { // not a registry url, must be direct invoke. 由于我们注册中心是写死在配置文件的,所以采用静态的 Directory
                    invoker = CLUSTER.join(new StaticDirectory(invokers));
                }
            }
        }

        if (shouldCheck() && !invoker.isAvailable()) {
            invoker.destroy();
            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());
        }
        if (logger.isInfoEnabled()) {
            logger.info("Refer dubbo service " + interfaceClass.getName() + " from url " + invoker.getUrl());
        }
        /**
         * @since 2.7.0
         * ServiceData Store
         */
        String metadata = map.get(METADATA_KEY);
        WritableMetadataService metadataService = WritableMetadataService.getExtension(metadata == null ? DEFAULT_METADATA_STORAGE_TYPE : metadata);
        if (metadataService != null) {
            URL consumerURL = new URL(CONSUMER_PROTOCOL, map.remove(REGISTER_IP_KEY), 0, map.get(INTERFACE_KEY), map);
            metadataService.publishServiceDefinition(consumerURL);
        }
        // create service proxy
        return (T) PROXY_FACTORY.getProxy(invoker, ProtocolUtils.isGeneric(generic));
}
  • 首先检查是不是本地调用,如果是,则使用injvm protocol的refer方法产生一个InjvmInvoker实例
  • 否则,再判断是否是点对点通信,也就是url参数不为空,而url参数又可以配置多个,所以这里需要遍历
  • 遍历所有注册中心的url,针对每个注册中心协议构建invoker,并保存到invokers中
  • 通过Cluster的StaticDirectory把多个静态注册中心组件成一个集群。

  在上面这个方法中,有两个核心的代码需要关注,分别是。

  1. REF_PROTOCOL.refer, 这个是生成invoker对象,之前我们说过,它是一个调用器,是dubbo中比较重要的领域对象,它在这里承担这服务调用的核心逻辑.
  2. PROXY_FACTORY.getProxy(invoker, ProtocolUtils.isGeneric(generic)), 构建一个代理对象,代理客户端的请求。

  我们先来分析refer方法。REF_PROTOCOL是一个自适应扩展点,现在我们看到这个代码,应该是比较熟悉了。它会生成一个Protocol$Adaptive的类,然后根据refer传递的的url参数来决定当前路由到哪个具体的协议处理器。

  前面我们分析服务发布的时候,已经说过了这个过程,不同的是这里会经过Wrapper 进行包装。先直接进入到RegistryProtocol.refer中

  RegistryProtocol这个类我们已经很熟悉了,服务注册和服务启动都是在这个类里面触发的。现在我们又通过这个方法来获得一个inovker对象,那我们继续去分析refer里面做了什么事情。

  • 组装注册中心协议的url
  • 判断是否配置了group,如果有,则cluster=getMergeableCluster(),构建invoker
  • doRefer构建invoker
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
     //获得注册中心的url地址,此时,这里得到的是zookeeper://
        url = getRegistryUrl(url);
     //这块跟服务发布的时候是一样的,返回一个 ZookeeperRegistry
        Registry registry = registryFactory.getRegistry(url);
        if (RegistryService.class.equals(type)) {
            return proxyFactory.getInvoker((T) registry, type, url);
        }

        // group="a,b" or group="*"
        Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY));
        String group = qs.get(GROUP_KEY);
        if (group != null && group.length() > 0) {
            if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) {
                return doRefer(getMergeableCluster(), registry, type, url);
            }
        }
        return doRefer(cluster, registry, type, url);
}

  doRefer方法创建一个RegistryDirectory实例,然后生成服务者消费者连接,并向注册中心进行注册。注册完毕后,紧接着订阅providers、configurators、roters等节点下的数据。完成订阅后,RegistryDirectory会收到到这几个节点下的子节点信息。由于一个服务可能部署在多台服务器上,这样就会在providers产生多个节点,这个时候就需要Cluster将多个服务节点合并为一个,并生成一个invoker。

private <T> Invoker<T> doRefer(Cluster cluster, Registry registry, Class<T> type, URL url) {
     //初始化RegistryDirectory
        RegistryDirectory<T> directory = new RegistryDirectory<T>(type, url);
        directory.setRegistry(registry);
        directory.setProtocol(protocol);
        // all attributes of REFER_KEY
        Map<String, String> parameters = new HashMap<String, String>(directory.getConsumerUrl().getParameters());
     //注册consumer://协议url
        URL subscribeUrl = new URL(CONSUMER_PROTOCOL, parameters.remove(REGISTER_IP_KEY), 0, type.getName(), parameters);
        if (directory.isShouldRegister()) {
         //注册服务消费者的url地址
            directory.setRegisteredConsumerUrl(subscribeUrl);
            registry.register(directory.getRegisteredConsumerUrl());
        }
        directory.buildRouterChain(subscribeUrl);
     //进行订阅
     //subscribe订阅信息消费url、通知监听、配置监听、订阅url
     //toSubscribeUrl:订阅信息:category、providers、configurators、routers
        directory.subscribe(toSubscribeUrl(subscribeUrl));
     //一个注册中心会存在多个服务提供者,所以在这里需要把多个服务提供者通过cluster.join合并成一个
        Invoker<T> invoker = cluster.join(directory);
        List<RegistryProtocolListener> listeners = findRegistryProtocolListeners(url);
        if (CollectionUtils.isEmpty(listeners)) {
            return invoker;
        }
     //通过RegistryInvokerWrapper进行包装
        RegistryInvokerWrapper<T> registryInvokerWrapper = new RegistryInvokerWrapper<>(directory, cluster, invoker, subscribeUrl);
        for (RegistryProtocolListener listener : listeners) {
            listener.onRefer(this, registryInvokerWrapper);
        }
        return registryInvokerWrapper;
}

  doRefer到底做了什么?只是初始化了一个RegistryDirectory,然后通过 Cluster.join 来返回一个Invoker对象?如果我们只需要关注核心流程,那么首先我们来看一下Cluster是什么?我们只关注一下Invoker这个代理类的创建过程,其他的暂且不关心

  cluster其实是在RegistryProtocol中通过set方法完成依赖注入的,Cluster是一个被依赖注入的自适应扩展点,注入的对象实例是一个Cluster$Adaptive的动态适配器类。并且,它还是一个被包装的

  在动态适配的类中会基于extName,选择一个合适的扩展点进行适配,由于默认情况下cluster:failover,所以getExtension("failover")理论上应该返回FailOverCluster。但实际上,这里做了包装MockClusterWrapper(FailOverCluster)

  所以再回到doRefer方法,下面这段代码, 实际是调用MockClusterWrapper(FailOverCluster.join),先走到 MockClusterWrapper#join

@Override
public <T> Invoker<T> join(Directory<T> directory) throws RpcException {
        return new MockClusterInvoker<T>(directory,
                this.cluster.join(directory));
}

  再调用AbstractCluster中的join方法,doJoin返回的是FailoverClusterInvoker。

public <T> Invoker<T> join(Directory<T> directory) throws RpcException {
    return buildClusterInterceptors(doJoin(directory), directory.getUrl().getParameter(REFERENCE_INTERCEPTOR_KEY));
}
public <T> AbstractClusterInvoker<T> doJoin(Directory<T> directory) throws RpcException {
        return new FailoverClusterInvoker<>(directory);
}

  buildClusterInterceptors:从名字可以看出,这里是构建一个Cluster的拦截器。

private <T> Invoker<T> buildClusterInterceptors(AbstractClusterInvoker<T> clusterInvoker, String key) {
        AbstractClusterInvoker<T> last = clusterInvoker;
     //通过激活扩展点来获得ClusterInterceptor集合. 如果没有配置激活参数,默认会有一个ConsumerContextClusterInterceptor拦截器.@Adaptive 注解在类上
        List<ClusterInterceptor> interceptors = ExtensionLoader.getExtensionLoader(ClusterInterceptor.class).getActivateExtension(clusterInvoker.getUrl(), key);
     //遍历拦截器集合,构建一个拦截器链.
        if (!interceptors.isEmpty()) {
            for (int i = interceptors.size() - 1; i >= 0; i--) {
                final ClusterInterceptor interceptor = interceptors.get(i);
                final AbstractClusterInvoker<T> next = last;
                last = new InterceptorInvokerNode<>(clusterInvoker, interceptor, next);
            }
        }
     //最终返回的last= InterceptorInvokerNode     
     // ConsumerContextClusterInterceptor -next- FailoverClusterInvoker
        return last;
}

   因此 Cluster.join,实际上是获得一个Invoker对象,这个Invoker实现了Directory的包装成了  MockClusterInvoker(AbstractCluster$InterceptorInvokerNode(FailoverClusterInvoker)) ,并且配置了拦截器。至于它是干嘛的,我们后续再分析。

构建远程服务的代理:

   返回了Invoker之后,再回到createProxy这段代码中,这里最终会调用一个getProxy来返回一个动态代理对象。并且这里把invoker作为参数传递进去,上面我们知道invoker这个对象的构建过程,实际上封装了一个directory在invoker中。

return (T) PROXY_FACTORY.getProxy(invoker, ProtocolUtils.isGeneric(generic)); 

  而这里的proxyFactory是一个自适应扩展点,它会根据url中携带的proxy参数来决定选择哪种动态代理技术来构建动态代理对象,默认是javassist

  JavassistProxyFactory#getProxy:通过这个方法生成了一个动态代理类,并且对invoker再做了一层处理,InvokerInvocationHandler。意味着后续发起服务调用的时候,会由InvokerInvocationHandler来进行处理。

public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
        return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker));
}

  至此,我们在分析服务消费者的动态代理的构建过程中可以发现,虽然代码非常非常的多,但是本质上就做了两件事情。

  1. 构建一个RegistryDirectory对象
  2. 生成远程服务的代理

  那么这里我们又要思考了,服务地址的获取呢? 远程通信的建立呢?如果这些步骤没有完成,因此我们又得往前面翻代码,去看看动态代理的构建过程中,是不是还有什么地方存在遗漏的呢?

RegistryDirectory 目录服务获取目标服务的url地址:

  在RegistryProtocol中,调用doRefer这个方法。这个doRefer方法中,构建了一个RegistryDirectory,它的作用很重要,它负责动态维护服务提供者列表。

  RegistryDirectory是Dubbo中的服务目录,从名字上来看,也比较容易理解,服务目录中存储了一些和服务提供者有关的信息,通过服务目录,服务消费者可获取到服务提供者的信息,比如 ip、端口、服务协议等。通过这些信息,服务消费者就可通过 Netty 等客户端进行远程调用。以下是它的类关系图.

  从这个图上不难发现,Dubbo提供了两种服务目录,一种是静态的,另一种是基于注册中心的。基于注册中心,那我们是不是清楚,注册中心会有一个动态更新服务列表的机制,因此RegistryDirectory实现了NotifyListener这个接口,也就是当服务地址发生变化时,RegistryDirectory中维护的地址列表需要及时变更。

  所以,再回忆一下之前我们通过Cluster.join去构建Invoker时,传递了一个directory进去,是不是也能够理解为什么这么做了呢?因为Invoker是一个调用器,在发起远程调用时,必然需要从directory中去拿到所有的服务提供者列表,然后再通过负载均衡机制来发起请求。

  订阅注册中心指定节点的变化,如果发生变化,则通知到RegistryDirectory。Directory其实和服务的注册以及服务的发现有非常大的关联.

public void subscribe(URL url) {
        setConsumerUrl(url);
        //把当前RegistryDirectory作为listener,去监听zk上节点的变化CONSUMER_CONFIGURATION_LISTENER.addNotifyListener(this);
        serviceConfigurationListener = new ReferenceConfigurationListener(this, url);
        registry.subscribe(url, this);//订阅 -> 这里的registry是zookeeperRegsitry
}

  此时,registry我们知道,它是ListenerRegistryWrapper(ZookeeperRegsistry)对象,我们先不管包装类,直接进入到ZookeeperRegistry这个类中,但是该类中未实现,所以直接进入其父类 FailbackRegistry#subscribe

  其中入参, listener为RegistryDirectory,后续要用到 failbackRegistry这个类,从名字就可以看出,它的主要作用就是实现具有故障恢复功能的服务订阅机制,简单来说就是如果在订阅服务注册中心时出现异常,会触发重试机制。

public void subscribe(URL url, NotifyListener listener) {
        super.subscribe(url, listener);
       //移除失效的listener,调用doSubscribe进行订阅
        removeFailedSubscribed(url, listener);
        try {
            // Sending a subscription request to the server side
            // 发送订阅请求到服务端
            doSubscribe(url, listener);
        } catch (Exception e) {
            Throwable t = e;

            List<URL> urls = getCacheUrls(url);
            if (CollectionUtils.isNotEmpty(urls)) {
                notify(url, listener, urls);
                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);
            } else {
                // If the startup detection is opened, the Exception is thrown directly.
                boolean check = getUrl().getParameter(Constants.CHECK_KEY, true)
                        && url.getParameter(Constants.CHECK_KEY, true);
                boolean skipFailback = t instanceof SkipFailbackWrapperException;
                if (check || skipFailback) {
                    if (skipFailback) {
                        t = t.getCause();
                    }
                    throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t);
                } else {
                    logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t);
                }
            }

            // Record a failed registration request to a failed list, retry regularly
            // 记录失败的注册订阅请求,根据规则进行重试
            addFailedSubscribed(url, listener);
        }
    }        

  ZookeeperRegistry.doSubscribe 这个方法是订阅,逻辑实现比较多,可以分两段来看,这里的实现把所有Service层发起的订阅以及指定的Service层发起的订阅分开处理。所有Service层类似于监控中心发起的订阅。指定的Service层发起的订阅可以看作是服务消费者的订阅。我们只需要关心指定service层发起的订阅即可

public void doSubscribe(final URL url, final NotifyListener listener) {
        try {
            //针对所有service层发起的定于
            if (ANY_VALUE.equals(url.getServiceInterface())) {
                String root = toRootPath();
                ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.computeIfAbsent(url, k -> new ConcurrentHashMap<>());
                ChildListener zkListener = listeners.computeIfAbsent(listener, k -> (parentPath, currentChilds) -> {
                    for (String child : currentChilds) {
                        child = URL.decode(child);
                        if (!anyServices.contains(child)) {
                            anyServices.add(child);
                            subscribe(url.setPath(child).addParameters(INTERFACE_KEY, child,
                                    Constants.CHECK_KEY, String.valueOf(false)), k);
                        }
                    }
                });
                zkClient.create(root, false);
                List<String> services = zkClient.addChildListener(root, zkListener);
                if (CollectionUtils.isNotEmpty(services)) {
                    for (String service : services) {
                        service = URL.decode(service);
                        anyServices.add(service);
                        subscribe(url.setPath(service).addParameters(INTERFACE_KEY, service,
                                Constants.CHECK_KEY, String.valueOf(false)), listener);
                    }
                }
            } else {
                //针对指定的服务地址发起订阅
                List<URL> urls = new ArrayList<>();
                //toCategoriesPath 会返回三个结果,分别是/providers、/configurations、/routers。 也就是服务启动时需要监听这三个节点下的数据变化
                for (String path : toCategoriesPath(url)) {
                    //构建一个listeners集合,其中key是NotifyListener,其中前面我们知道RegistryDirectory实现了这个接口,所以这里的key应该是RegistryDirectory
                    //value表示针对这个RegistryDirectory注册的子节点监听。
                    ConcurrentMap<NotifyListener, ChildListener> listeners = zkListeners.computeIfAbsent(url, k -> new ConcurrentHashMap<>());
                    ChildListener zkListener = listeners.computeIfAbsent(listener, k -> (parentPath, currentChilds) -> ZookeeperRegistry.this.notify(url, k, toUrlsWithEmpty(url, parentPath, currentChilds)));
                    zkClient.create(path, false);//创建一个/providers or/configurators、/routers节点
                    List<String> children = zkClient.addChildListener(path, zkListener);
                    if (children != null) {
                        urls.addAll(toUrlsWithEmpty(url, path, children));
                    }
                }
                //调用notify方法触发监听
                notify(url, listener, urls);
            }
        } catch (Throwable e) {
            throw new RpcException("Failed to subscribe " + url + " to zookeeper " + getUrl() + ", cause: " + e.getMessage(), e);
        }
}

  调用FailbackRegistry.notify, 对参数进行判断。 然后调用AbstractRegistry.notify方法。这里面会针对每一个category,调用listener.notify进行通知,然后更新本地的缓存文件

protected void notify(URL url, NotifyListener listener, List<URL> urls) {
        if (url == null) {
            throw new IllegalArgumentException("notify url == null");
        }
        if (listener == null) {
            throw new IllegalArgumentException("notify listener == null");
        }
        if ((CollectionUtils.isEmpty(urls))
                && !ANY_VALUE.equals(url.getServiceInterface())) {
            logger.warn("Ignore empty notify urls for subscribe url " + url);
            return;
        }
        if (logger.isInfoEnabled()) {
            logger.info("Notify urls for subscribe url " + url + ", urls: " + urls);
        }
        // keep every provider's category.
        Map<String, List<URL>> result = new HashMap<>();
        for (URL u : urls) {//urls表示三个empty://协议的地址
            if (UrlUtils.isMatch(url, u)) {
                String category = u.getParameter(CATEGORY_KEY, DEFAULT_CATEGORY);
                List<URL> categoryList = result.computeIfAbsent(category, k -> new ArrayList<>());
                categoryList.add(u);
            }
        }
        if (result.size() == 0) {
            return;
        }
        Map<String, List<URL>> categoryNotified = notified.computeIfAbsent(url, u -> new ConcurrentHashMap<>());
        for (Map.Entry<String, List<URL>> entry : result.entrySet()) {
            String category = entry.getKey();
            List<URL> categoryList = entry.getValue();
            categoryNotified.put(category, categoryList);
            listener.notify(categoryList);//通过listener监听categoryList
            // We will update our cache file after each notification.
            // When our Registry has a subscribe failure due to network jitter, we can return at least the existing cache URL.
            //保存到本地文件中,作为服务地址的缓存信息
            saveProperties(url);
        }
}    

  上述代码中,我们重点关注 listener.notify ,它会触发一个事件通知,消费端的listener是最开始传递过来的RegistryDirectory,所以这里会触发RegistryDirectory.notify

public synchronized void notify(List<URL> urls) {
        //对数据进行过滤
        Map<String, List<URL>> categoryUrls = urls.stream()
                .filter(Objects::nonNull)
                .filter(this::isValidCategory)
                .filter(this::isNotCompatibleFor26x)
                .collect(Collectors.groupingBy(this::judgeCategory));
        //假设当前进来的通知是 providers节点
        //判断configurator是否为空,这个节点下的配置,是在dubbo-admin控制台上修改配置时,会先创建一个配置节点到这个路径下,注册中心收到这个变化时会通知服务消费者,服务消费者会根据新的配置重新构建Invoker
        List<URL> configuratorURLs = categoryUrls.getOrDefault(CONFIGURATORS_CATEGORY, Collections.emptyList());
        this.configurators = Configurator.toConfigurators(configuratorURLs).orElse(this.configurators);
        //判断路由规则配置是否为空,如果不为空,同样将路由规则添加到url中。
        List<URL> routerURLs = categoryUrls.getOrDefault(ROUTERS_CATEGORY, Collections.emptyList());
        toRouters(routerURLs).ifPresent(this::addRouters);

        // providers
        // providers 得到服务提供者的地址列表
        List<URL> providerURLs = categoryUrls.getOrDefault(PROVIDERS_CATEGORY, Collections.emptyList());
        /**
         * 3.x added for extend URL address
         */
        ExtensionLoader<AddressListener> addressListenerExtensionLoader = ExtensionLoader.getExtensionLoader(AddressListener.class);
        //获得一个地址监听的激活扩展点。 这里目前应该还没有任何实现,可以先不用管
        List<AddressListener> supportedListeners = addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null);
        if (supportedListeners != null && !supportedListeners.isEmpty()) {
            for (AddressListener addressListener : supportedListeners) {
                providerURLs = addressListener.notify(providerURLs, getConsumerUrl(),this);
            }
        }
        refreshOverrideAndInvoker(providerURLs);
}

  refreshOverrideAndInvoker :逐个调用注册中心里面的配置,覆盖原来的url,组成最新的url 放入overrideDirectoryUrl 存储,此时我们没有在dubbo-admin中修改任何配置,所以这里没必要去分析

  根据 provider urls,重新刷新Invoker。直接进入 RegistryDirectory#refreshInvoker从名字可以看到,这里是刷新invoker。怎么理解呢?当注册中心的服务地址发生变化时,会触发更新。而更新之后并不是直接把url地址存储到内存,而是把url转化为invoker进行存储,这个invoker是作为通信的调用器来构建的领域对象,所以如果地址发生变化,那么需要把老的invoker销毁,然后用心的invoker替代。

private void refreshInvoker(List<URL> invokerUrls) {
        Assert.notNull(invokerUrls, "invokerUrls should not be null");
     //如果只有一个服务提供者,并且如果是空协议,那么这个时候直接返回进制访问,并且销毁所有的invokers
        if (invokerUrls.size() == 1
                && invokerUrls.get(0) != null
                && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
            this.forbidden = true; // Forbid to access
            this.invokers = Collections.emptyList();
            routerChain.setInvokers(this.invokers);
            destroyAllInvokers(); // Close all invokers
        } else {//第一次初始化的时候,invokerUrls为空。
            this.forbidden = false; // Allow to access
        //获取老的invoker集合

            Map<String, Invoker<T>> oldUrlInvokerMap = this.urlInvokerMap; // local reference
            if (invokerUrls == Collections.<URL>emptyList()) {
                invokerUrls = new ArrayList<>();//为null则初始化
            }
            if (invokerUrls.isEmpty() && this.cachedInvokerUrls != null) {
                invokerUrls.addAll(this.cachedInvokerUrls);
            } else {
                this.cachedInvokerUrls = new HashSet<>();
                this.cachedInvokerUrls.addAll(invokerUrls);//Cached invoker urls, convenient for comparison
            }
            if (invokerUrls.isEmpty()) {
                return;
            }
         //把invokerUrls转化为InvokerMap
            Map<String, Invoker<T>> newUrlInvokerMap = toInvokers(invokerUrls);// Translate url list to Invoker map

            /**
             * If the calculation is wrong, it is not processed.
             *
             * 1. The protocol configured by the client is inconsistent with the protocol of the server.
             *    eg: consumer protocol = dubbo, provider only has other protocol services(rest).
             * 2. The registration center is not robust and pushes illegal specification data.
             *
             */
            if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
                logger.error(new IllegalStateException("urls to invokers error .invokerUrls.size :" + invokerUrls.size() + ", invoker.size :0. urls :" + invokerUrls
                        .toString()));
                return;
            }
       //转化为list
            List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values()));
            // pre-route and build cache, notice that route cache should build on original Invoker list.
            // toMergeMethodInvokerMap() will wrap some invokers having different groups, those wrapped invokers not should be routed.
            routerChain.setInvokers(newInvokers);
        //如果服务配置了分组,则把分组下的provider包装成StaticDirectory,组成一个invoker
       //实际上就是按照group进行合并

            this.invokers = multiGroup ? toMergeInvokerList(newInvokers) : newInvokers;
            this.urlInvokerMap = newUrlInvokerMap;

            try {//旧的url 是否在新map里面存在,不存在,就是销毁url对应的Invoker
                destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker
            } catch (Exception e) {
                logger.warn("destroyUnusedInvokers error. ", e);
            }
        }
    }

  toInvokers:这个方法中有比较长的判断和处理逻辑,我们只需要关心invoker是什么时候初始化的就行。这里用到了protocol.refer来构建了一个invoker

invoker = new InvokerDelegate<>(protocol.refer(serviceType, url), url, providerUrl);
//构建完成之后,会保存
newUrlInvokerMap.put(key, invoker);

  简单总结一下,RegistryDirectory.subscribe,其实总的来说就相当于做了两件事

  1. 定于指定注册中心的以下三个路径的子节点变更事件/dubbo/org.apache.dubbo.demo.DemoService/providers、/dubbo/org.apache.dubbo.demo.DemoService/configurators、/dubbo/org.apache.dubbo.demo.DemoService/routers
  2. 触发时间变更之后,把变更的节点信息转化为Invoker

  Cluster.join这个操作,把RegistryDirectory作为参数传递进去了,那么是不是意味着返回的invoker中可以拿到真正的服务提供者地址,然后进行远程访问。

客户端服务通信的建立:

  protocol.refer:咱们继续往下看,在toInvokers这个方法中,invoker是通过 protocol.refer来构建的。那么我们再来分析一下refer里面做了什么?

  首先protocol,是被依赖注入进来的自适应扩展点Protocol$Adaptive. ,此时传进去的参数,此时url对应的地址应该是dubbo://开头的协议地址,所以最终获得的是通过包装之后的DubboProtocol对象。QosProtocolWrapper(ProtocolFilterWrapper(ProtocolListenerWrapper(DubboProtocol)))

  其中,在Qos这边,会启动Qosserver、在FilterWrapper中,会构建一个过滤器链,其中包含访问日志过滤、访问限制过滤等等,这个最终在调用的时候会通过一条过滤器链路对请求进行处理。

  DubboProtocol中没有refer方法,而是调用父类的refer。

@Override
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException {
        return new AsyncToSyncInvoker<>(protocolBindingRefer(type, url));
}

  protocolBindingRefer:主要做了两件事:

  1. 优化序列化
  2. 构建DubboInvoker

  在构建DubboInvoker时,会构建一个ExchangeClient,通过getClients(url)方法,这里基本可以猜到到是服务的通信建立。

@Override
public <T> Invoker<T> protocolBindingRefer(Class<T> serviceType, URL url) throws RpcException {
        // 构建序列化
        optimizeSerialization(url);
       
        // create rpc invoker.
        DubboInvoker<T> invoker = new DubboInvoker<T>(serviceType, url, getClients(url), invokers);
        invokers.add(invoker);

        return invoker;
}

  DubboProtocol#getClients:这里面是获得客户端连接的方法。判断是否为共享连接,默认是共享同一个连接进行通信,是否配置了多个连接通道 connections,默认只有一个共享连接。

private ExchangeClient[] getClients(URL url) {
        // whether to share connection

        boolean useShareConnect = false;

        int connections = url.getParameter(CONNECTIONS_KEY, 0);
        List<ReferenceCountExchangeClient> shareClients = null;
        // if not configured, connection is shared, otherwise, one connection for one service
        // 如果没有配置的情况下,默认是采用共享连接,否则,就是针对一个服务提供一个连接。
        if (connections == 0) {
            useShareConnect = true;

            /*
             * The xml configuration should have a higher priority than properties.
             */
            String shareConnectionsStr = url.getParameter(SHARE_CONNECTIONS_KEY, (String) null);
            connections = Integer.parseInt(StringUtils.isBlank(shareConnectionsStr) ? ConfigUtils.getProperty(SHARE_CONNECTIONS_KEY,
                    DEFAULT_SHARE_CONNECTIONS) : shareConnectionsStr);
            //返回共享连接
            shareClients = getSharedClient(url, connections);
        }
        //从共享连接中获得客户端连接进行返回
        ExchangeClient[] clients = new ExchangeClient[connections];
        for (int i = 0; i < clients.length; i++) {
            if (useShareConnect) {
                clients[i] = shareClients.get(i);

            } else {//如果不是使用共享连接,则初始化一个新的客户端连接进行返回
                clients[i] = initClient(url);
            }
        }

        return clients;
    }

  getSharedClient :获取共享连接:

private List<ReferenceCountExchangeClient> getSharedClient(URL url, int connectNum) {
        String key = url.getAddress();
        List<ReferenceCountExchangeClient> clients = referenceClientMap.get(key);
        //检查当前的key检查连接是否已经创建过并且可用,如果是,则直接返回并且增加连接的个数的统计
        if (checkClientCanUse(clients)) {
            batchClientRefIncr(clients);
            return clients;
        }
        //如果连接已经关闭或者连接没有创建过
        locks.putIfAbsent(key, new Object());
        synchronized (locks.get(key)) {
            clients = referenceClientMap.get(key);
            // dubbo check// 双重检查
            if (checkClientCanUse(clients)) {
                batchClientRefIncr(clients);
                return clients;
            }
            // 连接数必须大于等于1
            // connectNum must be greater than or equal to 1
            connectNum = Math.max(connectNum, 1);
            //如果当前消费者还没有和服务端产生连接,则初始化
            // If the clients is empty, then the first initialization is
            if (CollectionUtils.isEmpty(clients)) {
                clients = buildReferenceCountExchangeClientList(url, connectNum);
                referenceClientMap.put(key, clients);

            } else {//如果clients不为空,则从clients数组中进行遍历
                for (int i = 0; i < clients.size(); i++) {
                    ReferenceCountExchangeClient referenceCountExchangeClient = clients.get(i);
                    // If there is a client in the list that is no longer available, create a new one to replace him.
                    // 如果在集合中存在一个连接但是这个连接处于closed状态,则重新构建一个进行替换
                    if (referenceCountExchangeClient == null || referenceCountExchangeClient.isClosed()) {
                        clients.set(i, buildReferenceCountExchangeClient(url));
                        continue;
                    }

                    //增加个数
                    referenceCountExchangeClient.incrementAndGetCount();
                }
            }

            /*
             * I understand that the purpose of the remove operation here is to avoid the expired url key
             * always occupying this memory space.
             */
            locks.remove(key);

            return clients;
        }
}  

  buildReferenceCountExchangeClient:开始初始化客户端连接.也就是说,dubbo消费者在启动的时候,先从注册中心上加载最新的服务提供者地址,然后转化成invoker,但是转化的时候,也会同步去建立一个连接。而这个连接默认采用的是共享连接,因此就会存在对于同一个服务提供者,假设客户端依赖了多个@DubboReference,那么这个时候这些服务的引用会使用同一个连接进行通信。

  initClient:终于进入到初始化客户端连接的方法了,猜测应该是根据url中配置的参数进行远程通信的构建

private ExchangeClient initClient(URL url) {
      // 获取客户端通信类型,默认是netty
        // client type setting.
        String str = url.getParameter(CLIENT_KEY, url.getParameter(SERVER_KEY, DEFAULT_REMOTING_CLIENT));
        //获取编码解码类型,默认是Dubbo自定义类型
        url = url.addParameter(CODEC_KEY, DubboCodec.NAME);
        // enable heartbeat by default
       // 开启心跳并设置心跳间隔,默认60s

        url = url.addParameterIfAbsent(HEARTBEAT_KEY, String.valueOf(DEFAULT_HEARTBEAT));
     // 如果没有找到指定类型的通信扩展点,则抛出异常。
        // BIO is not allowed since it has severe performance issue.
        if (str != null && str.length() > 0 && !ExtensionLoader.getExtensionLoader(Transporter.class).hasExtension(str)) {
            throw new RpcException("Unsupported client type: " + str + "," +
                    " supported client type is " + StringUtils.join(ExtensionLoader.getExtensionLoader(Transporter.class).getSupportedExtensions(), " "));
        }

        ExchangeClient client;
        try {// 是否延迟建立连接
            // connection should be lazy
            if (url.getParameter(LAZY_CONNECT_KEY, false)) {
                client = new LazyConnectExchangeClient(url, requestHandler);

            } else {//默认是直接在启动时建立连接
                client = Exchangers.connect(url, requestHandler);
            }

        } catch (RemotingException e) {
            throw new RpcException("Fail to create remoting client for service(" + url + "): " + e.getMessage(), e);
        }

        return client;
}

  看到了 Exchangers 这个东东,是不是有点眼熟,在服务发布注册的源码里面也有这个类的参与,说明马上要通过Netty 进行连接了。

  果然是这样的。这里就不贴代码了,跟服务端的流程一摸一样。最后走到 org.apache.dubbo.remoting.transport.netty4.NettyTransporter#connect

@Override
public Client connect(URL url, ChannelHandler handler) throws RemotingException {
        return new NettyClient(url, handler);
}

  然后就是与服务端Netty 的连接过程了。总结:RegistryProtocol.refer 过程中有一个关键步骤,即在监听到服务提供者url时触发RegistryDirectory.notify() 方法。RegistryDirectory.notify() 方法调用 refreshInvoker() 方法将服务提供者urls转换为对应的 远程invoker ,最终调用到 DubboProtocol.refer() 方法生成对应的 DubboInvoker 。

DubboInvoker 的构造方法中有一项入参 ExchangeClient[] clients ,即对应本文要讲的网络客户端 Client 。DubboInvoker就是通过调用 client.request() 方法完成网络通信的请求发送和响应接收功能。Client 的具体生成过程就是通过 DubboProtocol 的 initClient(URL url) 方法创建了一个HeaderExchangeClient 。最后附上上述全流程流程图:

 

接口调用流程:

  客户端的调用很明显。需要用到代理类创建的时候的 Handler, JavassistProxyFactory#getProxy

@Override
@SuppressWarnings("unchecked")
public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {
        return (T) Proxy.getProxy(interfaces).newInstance(new InvokerInvocationHandler(invoker));
}

  一旦代码被调用,就会触发InvokerInvocationHandler.invoke.进入到InvokerInvocationHandler.invoke方法。

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(invoker, args);
        }//获取方法名
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 0) {
            if ("toString".equals(methodName)) {
                return invoker.toString();
            } else if ("$destroy".equals(methodName)) {
                invoker.destroy();
                return null;
            } else if ("hashCode".equals(methodName)) {
                return invoker.hashCode();
            }
        } else if (parameterTypes.length == 1 && "equals".equals(methodName)) {
            return invoker.equals(args[0]);
        }//构建请求实体类
        RpcInvocation rpcInvocation = new RpcInvocation(method, invoker.getInterface().getName(), args);
        String serviceKey = invoker.getUrl().getServiceKey();
        rpcInvocation.setTargetServiceUniqueName(serviceKey);
      
        if (consumerModel != null) {
            rpcInvocation.put(Constants.CONSUMER_MODEL, consumerModel);
            rpcInvocation.put(Constants.METHOD_MODEL, consumerModel.getMethodModel(method));
        }
       //发起调用
        return invoker.invoke(rpcInvocation).recreate();
    }

  其中invoker这个对象, 是在启动注入动态代理类时,初始化的一个调用器对象,我们得先要知道它是谁,才能知道它下一步调用的是哪个对象的方法.是: MockClusterInvoker(AbstractCluster$InterceptorInvokerNode(FailoverClusterInvoker)) ,因为它是通过MockClusterWrapper来进行包装的。

  所以这个 invoker.invoke 会先走 MockClusterInvoker#invoke。在这里面有两个逻辑

  1. 是否客户端强制配置了mock调用,那么在这种场景中主要可以用来解决服务端还没开发好的时候直接使用本地数据进行测试
  2. 是否出现了异常,如果出现异常则使用配置好的Mock类来实现服务的降级
public Result invoke(Invocation invocation) throws RpcException {
        Result result = null;

        String value = getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY, Boolean.FALSE.toString()).trim();
        if (value.length() == 0 || "false".equalsIgnoreCase(value)) {
            //no mock
            result = this.invoker.invoke(invocation);
        } else if (value.startsWith("force")) {
            if (logger.isWarnEnabled()) {
                logger.warn("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + getUrl());
            }
            //force:direct mock
            result = doMockInvoke(invocation, null);
        } else {
            //fail-mock
            try {
                result = this.invoker.invoke(invocation);

                //fix:#4585
                if(result.getException() != null && result.getException() instanceof RpcException){
                    RpcException rpcException= (RpcException)result.getException();
                    if(rpcException.isBiz()){
                        throw  rpcException;
                    }else {
                        result = doMockInvoke(invocation, rpcException);
                    }
                }

            } catch (RpcException e) {
                if (e.isBiz()) {
                    throw e;
                }

                if (logger.isWarnEnabled()) {
                    logger.warn("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + getUrl(), e);
                }
                result = doMockInvoke(invocation, e);
            }
        }
        return result;
}

  然后继续走 this.invoker.invoke ,即 AbstractCluster$InterceptorInvokerNode.invoker.为什么到这个类,看过前面生成动态代理过程的同学应该都知道,invoker会通过一个Interceptor进行包装。构建了一个拦截器链。

  这个拦截器是的组成是: ConsumerContextClusterInterceptor -next-> FailoverClusterInvoker, 当存在多注册中心的时候,这里会先走ZoneAwareClusterInvoker 进行注册中心的负载均衡进行区域路由,绕一圈再回来FailoverClusterInvoker

  其中before方法是设置上下文信息,接着调用interceptor.interceppt方法进行拦截处理

  调用ClusterInterceptor的默认方法。

default Result intercept(AbstractClusterInvoker<?> clusterInvoker, Invocation invocation) throws RpcException {
        return clusterInvoker.invoke(invocation);
}

  此时传递过来的clusterInvoker对象,是拦截器链中的第二个节点 FailoverClusterInvoker

  AbstractClusterInvoker#invoke:

public Result invoke(final Invocation invocation) throws RpcException {
        checkWhetherDestroyed();
        // 绑定attachment到invocation中
        // binding attachments into invocation.
        Map<String, Object> contextAttachments = RpcContext.getContext().getObjectAttachments();
        if (contextAttachments != null && contextAttachments.size() != 0) {
            ((RpcInvocation) invocation).addObjectAttachments(contextAttachments);
        }
        //获取invoker列表,这里的列表应该是直接从directory中获取
        List<Invoker<T>> invokers = list(invocation);
        //初始化负载均衡算法
        LoadBalance loadbalance = initLoadBalance(invokers, invocation);
        RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
        //调用子类的doInvoke方法
        return doInvoke(invocation, invokers, loadbalance);
}

  FailoverClusterInvoker.doInvoke:顾名思义,就是集群容错的处理,默认的集群容错策略是重试,所以也不难猜出这里面的实现方式。这段代码逻辑也很好理解,因为我们之前在讲Dubbo的时候说过容错机制,而failover是失败重试,所以这里面应该会实现容错的逻辑

  • 获得重试的次数,并且进行循环
  • 获得目标服务,并且记录当前已经调用过的目标服务防止下次继续将请求发送过去
  • 如果执行成功,则返回结果
  • 如果出现异常,判断是否为业务异常,如果是则抛出,否则,进行下一次重试
public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
        List<Invoker<T>> copyInvokers = invokers;
        checkInvokers(copyInvokers, invocation);//检查
        String methodName = RpcUtils.getMethodName(invocation);
        int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
        if (len <= 0) {
            len = 1;
        }
        // retry loop.
        RpcException le = null; // last exception.
        List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyInvokers.size()); // invoked invokers.
        Set<String> providers = new HashSet<String>(len);
        for (int i = 0; i < len; i++) {
            //Reselect before retry to avoid a change of candidate `invokers`.
            //NOTE: if `invokers` changed, then `invoked` also lose accuracy.
            if (i > 0) {
                checkWhetherDestroyed();
                copyInvokers = list(invocation);
                // check again
                checkInvokers(copyInvokers, invocation);
            }
          // 负载均衡选择
            Invoker<T> invoker = select(loadbalance, invocation, copyInvokers, invoked);
            invoked.add(invoker);
            RpcContext.getContext().setInvokers((List) invoked);
            try {//进行远程调用,走AbstractInvoker#invoke 
                Result result = invoker.invoke(invocation);
                if (le != null && logger.isWarnEnabled()) {
                    logger.warn("Although retry the method " + methodName
                            + " in the service " + getInterface().getName()
                            + " was successful by the provider " + invoker.getUrl().getAddress()
                            + ", but there have been failed providers " + providers
                            + " (" + providers.size() + "/" + copyInvokers.size()
                            + ") from the registry " + directory.getUrl().getAddress()
                            + " on the consumer " + NetUtils.getLocalHost()
                            + " using the dubbo version " + Version.getVersion() + ". Last error is: "
                            + le.getMessage(), le);
                }
                return result;
            } catch (RpcException e) {
                if (e.isBiz()) { // biz exception.
                    throw e;
                }
                le = e;
            } catch (Throwable e) {
                le = new RpcException(e.getMessage(), e);
            } finally {
                providers.add(invoker.getUrl().getAddress());
            }
        }
        throw new RpcException(le.getCode(), "Failed to invoke the method "
                + methodName + " in the service " + getInterface().getName()
                + ". Tried " + len + " times of the providers " + providers
                + " (" + providers.size() + "/" + copyInvokers.size()
                + ") from the registry " + directory.getUrl().getAddress()
                + " on the consumer " + NetUtils.getLocalHost() + " using the dubbo version "
                + Version.getVersion() + ". Last error is: "
                + le.getMessage(), le.getCause() != null ? le.getCause() : le);
}

  invoker对象的组成是: RegistryDirectory$InvokerDelegate() ->ListenerInvokerWrapper -> ProtocolFilterWrapper -> AsyncToSyncInvoker  -->DubboInvoker

  经过装饰器、过滤器对invoker进行增强和过滤之后,来到了AsyncToSyncInvoker.invoke方法,这里采用的是异步的方式来进行通信

public Result invoke(Invocation invocation) throws RpcException {
        Result asyncResult = invoker.invoke(invocation);

        try {
            //如果配置的是同步通信,则通过get阻塞式获取返回结果
            if (InvokeMode.SYNC == ((RpcInvocation) invocation).getInvokeMode()) {
                /**
                 * NOTICE!
                 * must call {@link java.util.concurrent.CompletableFuture#get(long, TimeUnit)} because
                 * {@link java.util.concurrent.CompletableFuture#get()} was proved to have serious performance drop.
                 */
                asyncResult.get(Integer.MAX_VALUE, TimeUnit.MILLISECONDS);
            }
        } catch (InterruptedException e) {
            throw new RpcException("Interrupted unexpectedly while waiting for remote result to return!  method: " +
                    invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
        } catch (ExecutionException e) {
            Throwable t = e.getCause();
            if (t instanceof TimeoutException) {
                throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " +
                        invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
            } else if (t instanceof RemotingException) {
                throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " +
                        invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
            } else {
                throw new RpcException(RpcException.UNKNOWN_EXCEPTION, "Fail to invoke remote method: " +
                        invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e);
            }
        } catch (Throwable e) {
            throw new RpcException(e.getMessage(), e);
        }
        return asyncResult;
}

  最后调用 DubboInvoker#doInvoke 发起远程调用。流程图如下

   最后的调用与老版本有一定的区别。详细参阅官方文档.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值