Dubbo進階(十一)- Dubbo 請求調用過程(一)

上一篇文章主要分析了消費者通過 獲取代理對象的詳細過程,以及對象內部原理,本文將從具體調用出發,一步一步深入Dubbo 調用內部細節。

前期鋪墊

博主這些文章對Dubbo 分析中,都是以API 調用爲例子進行,而本文分析消費者調用邏輯中,仍然是這樣,下面是相應代碼:

    public static void main(String[] args) {
        ReferenceConfig<HelloService> reference = new ReferenceConfig<>();
        reference.setApplication(new ApplicationConfig("dubbo-consumer"));
        reference.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
        reference.setInterface(HelloService.class);
        HelloService service = reference.get();
        String message = service.hello("dubbo I am anla7856");
        System.out.println(message);
    }

而上篇文章中,詳細的分析了 reference.get() 返回代理對象的構成:
在這裏插入圖片描述

InvokerInvocationHandler

在代理對象中,執行 hello 方法則是執行 proxy0.hello,即執行 InvokerInvocationHandlerinvoke 方法:

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(invoker, args);
        }
        // 判斷是否爲toString
        if ("toString".equals(methodName) && parameterTypes.length == 0) {
            return invoker.toString();
        }
        // 判斷是否爲hashCode
        if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
            return invoker.hashCode();
        }
        // 判斷是否爲equals
        if ("equals".equals(methodName) && parameterTypes.length == 1) {
            return invoker.equals(args[0]);
        }
		// 都不是則往下執行
        return invoker.invoke(new RpcInvocation(method, args)).recreate();
    }

以上方法依次判斷了以下幾個條件:

  1. 該方法對應的類如果是Object 類型,則直接執行該方法。
  2. 判斷是否爲toStringhashCodeequals,是則直接執行invoker 的對應方法
  3. 構造一個 RpcInvocation,用於執行invoker 的 invoker 方法,而RpcInvocation 的生層過程就是填充一些比如methodNameparameterTypesargumentsattachmentsinvoker 等信息。此invokerMockClusterInvoker

爲啥此 invokerMockClusterInvoker,可以看這篇:
Dubbo 消費者中 代理對象 初始化詳解

MockClusterInvoker

而後則會執行 MockClusterInvokerinvoker 方法:

    @Override
    public Result invoke(Invocation invocation) throws RpcException {
        Result result = null;
		// 判斷是否配置了 mock
        String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), MOCK_KEY, Boolean.FALSE.toString()).trim();
        if (value.length() == 0 || value.equalsIgnoreCase("false")) {
            // 沒有mock 則直接往下調用
            result = this.invoker.invoke(invocation);
        } else if (value.startsWith("force")) {
            // 有強制 mock配置,所以直接調用本地mock實現。
            if (logger.isWarnEnabled()) {
                logger.warn("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
            }
            result = doMockInvoke(invocation, null);
        } else {
            //當遠程調用失敗才調用的mock,即一種熔斷兜底的功能
            try {
                result = this.invoker.invoke(invocation);
            } catch (RpcException e) {
                if (e.isBiz()) {
                    throw e;
                }

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

上面 MockClusterInvoker 中的invoker 方法主要是對配置方法中mock 進行 區分性判斷。

  1. 當沒有配置mock,則直接往下調用 服務提供者暴露接口。
  2. 有配置強制mock 的化,那麼不進行遠端調用,而直接調用本地mock實現
  3. 有mock,則當調用服務提供者失敗時候,會使用本地mock實現兜底

本文將以無mock配置往下繼續分析

AbstractClusterInvoker

往後將會執行到AbstractClusterInvoker 的 invoke方法,即在上文代碼第一個if 就進入。

    public Result invoke(final Invocation invocation) throws RpcException {
    	// 判斷是否destroy
        checkWhetherDestroyed();

        // 從RpcContext中,查詢當前請求有沒有攜帶其他信息
        Map<String, String> contextAttachments = RpcContext.getContext().getAttachments();
        if (contextAttachments != null && contextAttachments.size() != 0) {
        // 有則加入進去
            ((RpcInvocation) invocation).addAttachments(contextAttachments);
        }
		// 通過Directory 獲取到所有可用的invoker
        List<Invoker<T>> invokers = list(invocation);
        // 初始化LoadBalance 的SPI ,默認使用的是 RandomLoadBanlance
        LoadBalance loadbalance = initLoadBalance(invokers, invocation);
        // 如果是異步調用,則需要 在Invocation 中增加一個id,用於標識這次Invocation
        RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
        // 執行子類doInvoke方法
        return doInvoke(invocation, invokers, loadbalance);
    }

AbstractClusterInvoker 中,主要是做一些準備性工作:

  1. 判斷是否被銷燬
  2. 判斷在 RpcContext.getContext() 是否有 attachments,有則需要加入到invocation中
  3. Directory 中 獲取 所有 Invoker,初始化LoadBalance(負載均衡)
  4. 如果指明是異步調用,則需要記錄下該次id做相應處理
  5. 執行子類的 doInvoker 方法

FailoverClusterInvoker

FailoverClusterInvoker 是一種輪詢的集羣策略,即當一個調用失敗時,會去請求另一個,Dubbo 中默認使用的就是這種集羣策略。
現在看看其doInvoke 方法:

    public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
       List<Invoker<T>> copyInvokers = invokers;
       // 檢查invokers,即檢查是否有可用的invokers
       checkInvokers(copyInvokers, invocation);
       // 獲取方法名
       String methodName = RpcUtils.getMethodName(invocation);
       // 獲取重試次數,默認有三次機會,最少有一次。
       int len = getUrl().getMethodParameter(methodName, RETRIES_KEY, DEFAULT_RETRIES) + 1;
       if (len <= 0) {
           len = 1;
       }
       // le 爲記錄最後一次錯誤。
       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.
           // 爲了保證準確性,除第一次外,每次循環,都需要重新檢查下invokers的活性
           // 一旦某個invoker失活,會被檢測到。
           if (i > 0) {
               checkWhetherDestroyed();
               copyInvokers = list(invocation);
               // check again
               checkInvokers(copyInvokers, invocation);
           }
           // 調用負載均衡,選擇出某一個invokers
           Invoker<T> invoker = select(loadbalance, invocation, copyInvokers, invoked);
           // 將選出的invoker加入,並存儲到上下文中。
           invoked.add(invoker);
           RpcContext.getContext().setInvokers((List) invoked);
           try {
           // 使用選出的invoker,執行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);
   }

上面代碼比較長,總結起來有以下幾步:

  1. 檢查 傳入的 invokers 活性,並根據其確定重試次數
  2. 第二次及以後循環,都需要重新檢查invokers 的最新活性,從而保證精準性
  3. 執行負載均衡邏輯選出invoker,並保存到上下文
  4. 使用選出的 invoker,執行其invoke方法,並獲取返回結果。

invoker.invoke(invocation)

整個就只有這一句了,使用 invoker去執行,包括超時,異步,網絡通信都在裏面,下面仔細分析。

  1. InvokerWrapperinvoke 方法
    首先進入的是InvokerWrapper 的invoke方法,裏面則僅僅包裝一層,是直接執行invoker.invoke 方法。
    @Override
    public Result invoke(Invocation invocation) throws RpcException {
        return invoker.invoke(invocation);
    }

下面結合 invoker 圖來分析。
在這裏插入圖片描述
2. ProtocolFilterWrapperinvoke 方法:

        @Override
        public Result invoke(Invocation invocation) throws RpcException {
        // 異步使用filterInvoker 執行invoke
            Result asyncResult = filterInvoker.invoke(invocation);

            asyncResult.thenApplyWithContext(r -> {
                for (int i = filters.size() - 1; i >= 0; i--) {
                    Filter filter = filters.get(i);
                    // onResponse callback
                    if (filter instanceof ListenableFilter) {
                        Filter.Listener listener = ((ListenableFilter) filter).listener();
                        if (listener != null) {
                            listener.onResponse(r, filterInvoker, invocation);
                        }
                    } else {
                        filter.onResponse(r, filterInvoker, invocation);
                    }
                }
                return r;
            });

            return asyncResult;
        }

ProtocolFilterWrapper 的invoke方法其實邏輯比較複雜,Result asyncResult = filterInvoker.invoke(invocation); 裏面執行了ProtocolFilterWraper 中所有相關鏈式的 Filter
主要有哪些Filter呢?又是如何初始化的呢?

ProtocolFilterWrapper 中 Filter 構建

ProtocolFilterWrapper 執行 refer 初始化時,會執行 buildInvokerChain 方法,而 ProtocolFilterWrapperFilter 就是在這裏面構建的:

    private static <T> Invoker<T> buildInvokerChain(final Invoker<T> invoker, String key, String group) {
        Invoker<T> last = invoker;
        // 獲取所有符合要求的Filter
        List<Filter> filters = ExtensionLoader.getExtensionLoader(Filter.class).getActivateExtension(invoker.getUrl(), key, group);

        if (!filters.isEmpty()) {
            for (int i = filters.size() - 1; i >= 0; i--) {
                final Filter filter = filters.get(i);
                final Invoker<T> next = last;
                last = new Invoker<T>() {

                    @Override
                    public Class<T> getInterface() {
                        return invoker.getInterface();
                    }

                    @Override
                    public URL getUrl() {
                        return invoker.getUrl();
                    }

                    @Override
                    public boolean isAvailable() {
                        return invoker.isAvailable();
                    }

                    @Override
                    public Result invoke(Invocation invocation) throws RpcException {
                        Result asyncResult;
                        try {
                            asyncResult = filter.invoke(next, invocation);
                        } catch (Exception e) {
                            // onError callback
                            if (filter instanceof ListenableFilter) {
                                Filter.Listener listener = ((ListenableFilter) filter).listener();
                                if (listener != null) {
                                    listener.onError(e, invoker, invocation);
                                }
                            }
                            throw e;
                        }
                        return asyncResult;
                    }

                    @Override
                    public void destroy() {
                        invoker.destroy();
                    }

                    @Override
                    public String toString() {
                        return invoker.toString();
                    }
                };
            }
        }

        return new CallbackRegistrationInvoker<>(last, filters);
    }

初始化邏輯也簡單,主要關心下有哪些Filter 被選中,並且組件順序(類加載本就無法保證順序,但是可以通過order 參數排序),而一大塊實現,則只是執行Filterinvoke方法

在 dubbo filter中,有以下一些SPI 類:

echo=org.apache.dubbo.rpc.filter.EchoFilter    # provider  -110000
generic=org.apache.dubbo.rpc.filter.GenericFilter  # provider  -20000
genericimpl=org.apache.dubbo.rpc.filter.GenericImplFilter  # consumer  20000
token=org.apache.dubbo.rpc.filter.TokenFilter
accesslog=org.apache.dubbo.rpc.filter.AccessLogFilter # provider 
activelimit=org.apache.dubbo.rpc.filter.ActiveLimitFilter  # consumer 
classloader=org.apache.dubbo.rpc.filter.ClassLoaderFilter  # provider -30000
context=org.apache.dubbo.rpc.filter.ContextFilter  # provider -10000
consumercontext=org.apache.dubbo.rpc.filter.ConsumerContextFilter   # consumer -10000
exception=org.apache.dubbo.rpc.filter.ExceptionFilter   # provider
executelimit=org.apache.dubbo.rpc.filter.ExecuteLimitFilter  # provider
deprecated=org.apache.dubbo.rpc.filter.DeprecatedFilter   # consumer 
compatible=org.apache.dubbo.rpc.filter.CompatibleFilter  # provider,consumer
timeout=org.apache.dubbo.rpc.filter.TimeoutFilter   # provider
...

在這裏插入圖片描述
上述Filter 中,選中有兩個條件:

  1. @Activate 修飾
  2. url中有指定,或者@Activate 中 value 爲空的
  3. group 這邊,ProtocolFilterWrapper 主要體現爲 consumer
  4. 如果有傳入 names,則需要對names進行進一層篩選,此處如果是加入該name對應的spi,如果是default類型,則需要將該SPI 放到最前面。

最終,有三個Filter 脫穎而出,順序依次是:ConsumerContextFilterMonitorFilterFutureFilter(排序順序,order 越小月往前)

下文

如今已經知道了ProtocolFilterWrapper 裏面 filter 邏輯了,下一篇文章則繼續驗證 ProtocolFilterWrapper 的filter 調用邏輯走。

覺得博主寫的有用,不妨關注博主公衆號: 六點A君。
哈哈哈,Dubbo小吃街不迷路:
在這裏插入圖片描述

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