dubbo源碼解析——消費過程

上一篇 dubbo源碼解析——概要篇中我們瞭解到dubbo中的一些概念及消費端總體調用過程。本文中,將進入消費端源碼解析(具體邏輯會放到代碼的註釋中)。本文先是對消費過程的總體代碼邏輯理一遍,個別需要細講的點,後面會專門的文章進行解析。

開頭進入InvokerInvocationHandler

通過實現InvocationHandler,我們知道dubbo生成代理使用的是JDK動態代理。這個類中主要是對特殊方法進行處理。由於在生成代理實例的時候,在構造函數中賦值了invoker,因此可以只用該invoker進行invoke方法的調用。

/**
 * dubbo使用JDK動態代理,對接口對象進行注入
 * InvokerHandler
 *
 * 程序啓動的過程中,在構造函數中,賦值下一個需要調用的invoker,從而形成執行鏈
 */
public class InvokerInvocationHandler implements InvocationHandler {

    private final Invoker<?> invoker;

    public InvokerInvocationHandler(Invoker<?> handler) {
        this.invoker = handler;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 獲取方法名稱
        String methodName = method.getName();
        // 獲取參數類型
        Class<?>[] parameterTypes = method.getParameterTypes();
        // 方法所處的類 是 Object類,則直接調用
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(invoker, args);
        }

        /*
         * toString、hashCode、equals方法比較特殊,如果interface裏面定義了這幾個方法,並且進行實現,
         * 通過dubbo遠程調用是不會執行這些代碼實現的。
         */

        /*
         * 方法調用是toString,依次執行MockClusterInvoker、AbstractClusterInvoker的toString方法
         */
        if ("toString".equals(methodName) && parameterTypes.length == 0) {
            return invoker.toString();
        }

        /*
         * interface中含有hashCode方法,直接調用invoker的hashCode
         */
        if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
            return invoker.hashCode();
        }

        /*
         * interface中含有equals方法,直接調用invoker的equals
         */
        if ("equals".equals(methodName) && parameterTypes.length == 1) {
            return invoker.equals(args[0]);
        }

        /*
         * invocationv包含了遠程調用的參數、方法信息
         */
        RpcInvocation invocation;

        /*
         * todo這段代碼在最新的dubbo版本中沒有
         */
        if (RpcUtils.hasGeneratedFuture(method)) {
            Class<?> clazz = method.getDeclaringClass();
            String syncMethodName = methodName.substring(0, methodName.length() - Constants.ASYNC_SUFFIX.length());
            Method syncMethod = clazz.getMethod(syncMethodName, method.getParameterTypes());
            invocation = new RpcInvocation(syncMethod, args);
            invocation.setAttachment(Constants.FUTURE_GENERATED_KEY, "true");
            invocation.setAttachment(Constants.ASYNC_KEY, "true");
        } else {
            invocation = new RpcInvocation(method, args);
            if (RpcUtils.hasFutureReturnType(method)) {
                invocation.setAttachment(Constants.FUTURE_RETURNTYPE_KEY, "true");
                invocation.setAttachment(Constants.ASYNC_KEY, "true");
            }
        }

        // 繼續invoker鏈式調用
        return invoker.invoke(invocation).recreate();
    }


}

進入MockClusterInvoker

這段代碼主要是判斷是否需要進行mock調用

@Override
    public Result invoke(Invocation invocation) throws RpcException {
        Result result = null;

        // 獲取mock參數,從而判斷是否需要mock
        String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim();

        if (value.length() == 0 || value.equalsIgnoreCase("false")) {
            // 不需要mock,繼續往下調用
            result = this.invoker.invoke(invocation);
        } else if (value.startsWith("force")) {
            if (logger.isWarnEnabled()) {
                logger.warn("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl());
            }
            // 選擇mock的invoker
            result = doMockInvoke(invocation, null);
        } else {
            // 正常調用失敗,則調用mock
            try {
                result = this.invoker.invoke(invocation);
            } catch (RpcException e) {
                if (e.isBiz()) {
                    throw e;
                } else {
                    if (logger.isWarnEnabled()) {
                        logger.warn("fail-mock: " + invocation.getMethodName() + " fail-mock enabled , url : " + directory.getUrl(), e);
                    }
                    result = doMockInvoke(invocation, e);
                }
            }
        }
        return result;
    }

進入AbstractClusterInvoker

進入這段代碼,表明開始進入到集羣

@Override
    public Result invoke(final Invocation invocation) throws RpcException {
        // 檢查消費端invoker是否銷燬了
        checkWhetherDestroyed();

        // 將參數綁定到invocation
        Map<String, String> contextAttachments = RpcContext.getContext().getAttachments();
        if (contextAttachments != null && contextAttachments.size() != 0) {
            ((RpcInvocation) invocation).addAttachments(contextAttachments);
        }

        // 獲取滿足條件的invoker(從Directory獲取,並且經過router過濾)
        List<Invoker<T>> invokers = list(invocation);

        // 初始化loadBalance
        LoadBalance loadbalance = initLoadBalance(invokers, invocation);

        // invocation ID將被添加在異步操作
        RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);

        return doInvoke(invocation, invokers, loadbalance);
    }

進入AbstractDirectory

@Override
    public List<Invoker<T>> list(Invocation invocation) throws RpcException {
        // 判斷Directory是否銷燬
        if (destroyed) {
            throw new RpcException("Directory already destroyed .url: " + getUrl());
        }
        // 從methodInvokerMap中取出滿足條件的invoker
        List<Invoker<T>> invokers = doList(invocation);

        // 根據路由列表,篩選出滿足條件的invoker
        List<Router> localRouters = this.routers; // local reference
        if (localRouters != null && !localRouters.isEmpty()) {
            for (Router router : localRouters) {
                try {
                    if (router.getUrl() == null || router.getUrl().getParameter(Constants.RUNTIME_KEY, false)) {
                        invokers = router.route(invokers, getConsumerUrl(), invocation);
                    }
                } catch (Throwable t) {
                    logger.error("Failed to execute router: " + getUrl() + ", cause: " + t.getMessage(), t);
                }
            }
        }
        return invokers;
    }

這裏主要是從Directory中獲取invoker,並且經過router路由的篩選,獲得滿足條件的invoker。
在AbstractDirectory中,有一個關鍵的方法com.alibaba.dubbo.rpc.cluster.directory.AbstractDirectory#doList,這是一個抽象方法,子類RegistryDirectory的有具體實現,並且調用RegistryDirectory的doList方法。(這裏應該是用到了模板方法模式)。後面的文字中會詳細講下doList方法中做了啥。

進入FailoverClusterInvoker

經過從Directory中獲取invoker,然後router篩選出滿足條件的invoker之後,進入到FailoverClusterInvoker。爲什麼會到這裏呢?

根據官網的描述:
在集羣調用失敗時,Dubbo 提供了多種容錯方案,缺省爲 failover 重試。
所以這個時候是到了FailoverClusterInvoker類,但是如果你配置的是Failfast Cluster(快速失敗),Failsafe Cluster(失敗安全),Failback Cluster(失敗自動恢復),Forking Cluster(並行調用多個服務器,只要一個成功即返回),Broadcast Cluster(廣播調用所有提供者,逐個調用,任意一臺報錯則報錯),他也會到達相應的類。

@Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    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, Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1;
        if (len <= 0) {
            // 最少要調用1次
            len = 1;
        }

        // 局部引用
        RpcException le = null;
        List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyinvokers.size()); // invoked invokers.
        Set<String> providers = new HashSet<String>(len);

        // i < len 作爲循環條件,說明len是多少就循環多少次
        for (int i = 0; i < len; i++) {
            // 在重試之前,需要重新選擇,以避免候選invoker的改變
            if (i > 0) {
                // 檢查invoker是否被銷燬
                checkWhetherDestroyed();
                // 重新選擇invoker
                copyinvokers = list(invocation);
                // 參數檢查
                checkInvokers(copyinvokers, invocation);
            }

            /*
             * 這一步就是進入loadBalance負載均衡
             * 因爲上述步驟可能篩選出invoker數量大於1,所以再次經過loadBalance的篩選
             */
            Invoker<T> invoker = select(loadbalance, invocation, copyinvokers, invoked);
            invoked.add(invoker);

            RpcContext.getContext().setInvokers((List) invoked);
            try {
                // 遠程方法調用
                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 != null ? le.getCode() : 0, "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 != null ? le.getMessage() : ""), le != null && le.getCause() != null ? le.getCause() : le);
    }

到達終點站.我們回憶總結一下,文初提到的三個關鍵詞,在這個集羣容錯的整體架構過程中,dubbo究竟做了什麼.其實也就是三件事

(1)在Directory中找出本次集羣中的全部invokers
(2)在Router中,將上一步的全部invokers挑選出能正常執行的invokers
(3)在LoadBalance中,將上一步的能正常的執行invokers中,根據配置的負載均衡策略,挑選出需要執行的invoker

後面的文章中,對上述的一些細節進行解析

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