1. 程式人生 > >Dubbo原始碼解析之consumer呼叫篇

Dubbo原始碼解析之consumer呼叫篇

閱讀須知

  • dubbo版本:2.6.0
  • spring版本:4.3.8
  • 文章中使用/* */註釋的方法會做深入分析

正文

在分析consumer初始化時,我們看到了關聯服務引用建立代理的過程,最終會呼叫JavassistProxyFactory的getProxy方法來建立代理,並用InvokerInvocationHandler對Invoker進行了包裝,InvokerInvocationHandler實現了JDK的InvocationHandler,這個介面相信熟悉JDK動態代理的同學一定不陌生,所以我們在呼叫服務的方法時就會呼叫其invoke方法,我們來看實現:
InvokerInvocationHandler:

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);
    }
    if
("toString".equals(methodName) && parameterTypes.length == 0) { return invoker.toString(); } if ("hashCode".equals(methodName) && parameterTypes.length == 0) { return invoker.hashCode(); } if ("equals".equals(methodName) && parameterTypes.length ==
1) { return invoker.equals(args[0]); } /* 將方法和引數封裝到RpcInvocation中,呼叫Invoker的invoke方法 */ return invoker.invoke(new RpcInvocation(method, args)).recreate(); }

這裡的Invoker我們在也分析consumer初始化時同樣看到過,是由FailoverCluster的FailoverClusterInvoker:
AbstractClusterInvoker:

public Result invoke(final Invocation invocation) throws RpcException {
    checkWhetherDestroyed(); // 檢查invoker是否已經銷燬
    LoadBalance loadbalance;
    /* 獲取invoker集合 */
    List<Invoker<T>> invokers = list(invocation);
    if (invokers != null && invokers.size() > 0) {
        // 獲取負載均衡策略,預設為隨機
        loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl()
                .getMethodParameter(invocation.getMethodName(), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE));
    } else {
        loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(Constants.DEFAULT_LOADBALANCE);
    }
    // 冪等操作:預設情況下,將在非同步操作中新增呼叫ID
    RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation);
    /* 呼叫 */
    return doInvoke(invocation, invokers, loadbalance);
}

AbstractClusterInvoker:

protected List<Invoker<T>> list(Invocation invocation) throws RpcException {
    /* 這裡的directory在RegistryProtocol的doRefer方法中構建Invoker時傳入,為RegistryDirectory */
    List<Invoker<T>> invokers = directory.list(invocation);
    return invokers;
}

AbstractDirectory:

public List<Invoker<T>> list(Invocation invocation) throws RpcException {
    if (destroyed) {
        throw new RpcException("Directory already destroyed .url: " + getUrl());
    }
    /* 獲取invoker */
    List<Invoker<T>> invokers = doList(invocation);
    // 路由處理,筆者的環境中Router集合中只有MockInvokersSelector,用來處理mock服務
    List<Router> localRouters = this.routers;
    if (localRouters != null && localRouters.size() > 0) {
        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;
}

RegistryDirectory:

public List<Invoker<T>> doList(Invocation invocation) {
    if (forbidden) {
        throw new RpcException(RpcException.FORBIDDEN_EXCEPTION,
            "No provider available from registry " + getUrl().getAddress() + " for service " + getConsumerUrl().getServiceKey() + " on consumer " +  NetUtils.getLocalHost()
                + " use dubbo version " + Version.getVersion() + ", may be providers disabled or not registered ?");
    }
    List<Invoker<T>> invokers = null;
    // 這裡的methodInvokerMap在consumer初始化時訂閱註冊中心的providers、configuration等相關資訊時收到通知時初始化
    Map<String, List<Invoker<T>>> localMethodInvokerMap = this.methodInvokerMap;
    if (localMethodInvokerMap != null && localMethodInvokerMap.size() > 0) {
        String methodName = RpcUtils.getMethodName(invocation);
        Object[] args = RpcUtils.getArguments(invocation);
        // 依次採用不同的方式從map中獲取invoker
        if (args != null && args.length > 0 && args[0] != null
                && (args[0] instanceof String || args[0].getClass().isEnum())) {
            invokers = localMethodInvokerMap.get(methodName + "." + args[0]);
        }
        if (invokers == null) {
            invokers = localMethodInvokerMap.get(methodName);
        }
        if (invokers == null) {
            invokers = localMethodInvokerMap.get(Constants.ANY_VALUE);
        }
        if (invokers == null) {
            Iterator<List<Invoker<T>>> iterator = localMethodInvokerMap.values().iterator();
            if (iterator.hasNext()) {
                invokers = iterator.next();
            }
        }
    }
    return invokers == null ? new ArrayList<Invoker<T>>(0) : invokers;
}

FailoverClusterInvoker:

public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {
    List<Invoker<T>> copyinvokers = invokers;
    checkInvokers(copyinvokers, invocation);
    // 重試次數,第一次呼叫不算重試,所以加1
    int len = getUrl().getMethodParameter(invocation.getMethodName(), Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1;
    if (len <= 0) {
        len = 1;
    }
    RpcException le = null;
    // 儲存已經呼叫過的invoker
    List<Invoker<T>> invoked = new ArrayList<Invoker<T>>(copyinvokers.size());
    Set<String> providers = new HashSet<String>(len);
    // 重試迴圈
    for (int i = 0; i < len; i++) {
        // 在重試之前重新選擇以避免候選invokers的更改
        // 注意:如果invokers改變了,那麼invoked集合也會失去準確性
        if (i > 0) {
            // 重複第一次呼叫的幾個步驟
            checkWhetherDestroyed();
            copyinvokers = list(invocation);
            checkInvokers(copyinvokers, invocation);
        }
        /* 選擇一個invoker */
        Invoker<T> invoker = select(loadbalance, invocation, copyinvokers, invoked);
        invoked.add(invoker);
        RpcContext.getContext().setInvokers((List) invoked);
        try {
            /* 呼叫invoke方法返回結果 */
            Result result = invoker.invoke(invocation);
            if (le != null && logger.isWarnEnabled()) {
                logger.warn("Although retry the method " + invocation.getMethodName()
                        + " 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()) {
                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 "
            + invocation.getMethodName() + " 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);
}

AbstractClusterInvoker:

protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
    if (invokers == null || invokers.size() == 0)
        return null;
    String methodName = invocation == null ? "" : invocation.getMethodName();
    boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY);
    {
        // 忽略過載方法
        if (stickyInvoker != null && !invokers.contains(stickyInvoker)) {
            stickyInvoker = null;
        }
        // 忽略併發問題
        if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) {
            if (availablecheck && stickyInvoker.isAvailable()) {
                return stickyInvoker;
            }
        }
    }
    /* 使用負載均衡策略選擇invoker */
    Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected);
    if (sticky) {
        stickyInvoker = invoker;
    }
    return invoker;
}

AbstractClusterInvoker:

private Invoker<T> doselect(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException {
    if (invokers == null || invokers.size() == 0)
        return null;
    if (invokers.size() == 1)
        return invokers.get(0); // 只有一個invoker直接返回
    // 如果只有兩個invoker,使用輪詢策略
    if (invokers.size() == 2 && selected != null && selected.size() > 0) {
        return selected.get(0) == invokers.get(0) ? invokers.get(1) : invokers.get(0);
    }
    // 負載均衡策略選擇invoker
    Invoker<T> invoker = loadbalance.select(invokers, getUrl(), invocation);
    // 如果invoker在selected中或者invoker不可用並且availablecheck為true,則重新選擇
    if ((selected != null && selected.contains(invoker))
            || (!invoker.isAvailable() && getUrl() != null && availablecheck)) {
        try {
            /* 重新選擇 */
            Invoker<T> rinvoker = reselect(loadbalance, invocation, invokers, selected, availablecheck);
            if (rinvoker != null) {
                invoker = rinvoker;
            } else {
                int index = invokers.indexOf(invoker);
                try {
                    // 檢查當前所選invoker的index,如果不是最後一個,請選擇索引為index + 1的invoker
                    invoker = index < invokers.size() - 1 ? invokers.get(index + 1) : invoker;
                } catch (Exception e) {
                    logger.warn(e.getMessage() + " may because invokers list dynamic change, ignore.", e);
                }
            }
        } catch (Throwable t) {
            logger.error("clustor relselect fail reason is :" + t.getMessage() + " if can not slove ,you can set