深入Dubbo源码 – Dubbo消费者调用过程
- 2019 年 10 月 5 日
- 筆記
之前已经学习了, Dubbo
是怎样加载配置文件的,怎样初始化 Bean
的。那只是 Dubbo
真正运行的准备工作,并不设计 Dubbo
的核心,笔者也并不是很了解,只是为了面试而准备的那些泛泛而谈。现在一步步的来研究学习,记录下 Dubbo
的调用过程,在关键代码处添加个人的理解,希望对 大家有所帮助。
调用过程
代理类Invoke
// 该类实现InvocationHandler接口,在调用动态代理类方法时会调用invoke方法 @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); } 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]); } // 如果是调用基础方法,直接调用invoker的方法并返回。调用其他方法,则将本次调用信息封装成RpcInvocation对象 // (详见下文) return invoker.invoke(new RpcInvocation(method, args)).recreate(); }
注:
- 想要了解动态代理的demo可以查看此处。
MockClusterInvoker执行invoke方法
@Override public Result invoke(Invocation invocation) throws RpcException { Result result = null; // 从directory中获取调用的方法信息中存储的配置信息Constants.MOCK_KEY(是否使用mock模式,默认为false) String value = directory.getUrl().getMethodParameter(invocation.getMethodName(), Constants.MOCK_KEY, Boolean.FALSE.toString()).trim(); // 如果为false,则调用真实服务提供者 if (value.length() == 0 || value.equalsIgnoreCase("false")) { //no mock result = this.invoker.invoke(invocation); } else if (value.startsWith("force")) {// 如果该配置以force开头,则进行强制mock调用,执行doMockInvoke方法(具体可查看方法内实现,该内容不是本文重点) if (logger.isWarnEnabled()) { logger.info("force-mock: " + invocation.getMethodName() + " force-mock enabled , url : " + directory.getUrl()); } //force:direct mock result = doMockInvoke(invocation, null); } else {// 其他配置,则优先调用服务提供者,如果失败再进行mock //fail-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); } // 会catch RpcException异常,失败后执行doMockInvoke方法 result = doMockInvoke(invocation, e); } } } return result; }
AbstractClusterInvoker执行invoke方法
@Override public Result invoke(final Invocation invocation) throws RpcException { checkWhetherDestroyed(); LoadBalance loadbalance = null; // 查看线程变量InternalThreadLocal中获取上下文对象RpcContext,查看RpcContext中是否有"附件"属性,如果有,则本次调用invocation加入该属性 // binding attachments into invocation. Map<String, String> contextAttachments = RpcContext.getContext().getAttachments(); if (contextAttachments != null && contextAttachments.size() != 0) { ((RpcInvocation) invocation).addAttachments(contextAttachments); } // 从directory中获取invokers list(查看directory对象,该list可通过notify方法与注册中心交互更新) List<Invoker<T>> invokers = list(invocation); if (invokers != null && !invokers.isEmpty()) { // 获取负载均衡策略,未配置则默认随机策略RandomLoadBalance loadbalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(invokers.get(0).getUrl() .getMethodParameter(RpcUtils.getMethodName(invocation), Constants.LOADBALANCE_KEY, Constants.DEFAULT_LOADBALANCE)); } RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); // 执行子类doInvoke方法(详见下文) return doInvoke(invocation, invokers, loadbalance); }
AbstractClusterInvoker子类FailoverClusterInvoker执行doInvoke方法
public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException { List<Invoker<T>> copyinvokers = invokers; // 检查invokers,为空则抛出异常RpcException checkInvokers(copyinvokers, invocation); // 获取重试次数,默认是2次 int len = getUrl().getMethodParameter(invocation.getMethodName(), Constants.RETRIES_KEY, Constants.DEFAULT_RETRIES) + 1; // 如果配置不当,则将次数置为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 再一次检查,防止在调用过程中list中的invoker变化 checkInvokers(copyinvokers, invocation); } // 通过不同的负载均衡策略选择一个invoker Invoker<T> invoker = select(loadbalance, invocation, copyinvokers, invoked); // 将已经选择出的invoker存放在另一个list中 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 " + 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()) { // 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 " + 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); }
ConsumerContextFilter执行invoke方法
@Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { // 用RpcContext存储调用的上下文信息 RpcContext.getContext() .setInvoker(invoker) .setInvocation(invocation) .setLocalAddress(NetUtils.getLocalHost(), 0) .setRemoteAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(invoker); } try { // (详见下文) RpcResult result = (RpcResult) invoker.invoke(invocation); RpcContext.getServerContext().setAttachments(result.getAttachments()); return result; } finally { // 清除上下文RpcContext中存储的“附件”信息 RpcContext.getContext().clearAttachments(); } }
FutureFilter执行invoke方法
@Override public Result invoke(final Invoker<?> invoker, final Invocation invocation) throws RpcException { // 此次调用是否是异步调用 final boolean isAsync = RpcUtils.isAsync(invoker.getUrl(), invocation); fireInvokeCallback(invoker, invocation); // need to configure if there's return value before the invocation in order to help invoker to judge if it's // necessary to return future. Result result = invoker.invoke(invocation); if (isAsync) { // 异步调用 asyncCallback(invoker, invocation); } else { // 同步调用(默认) syncCallback(invoker, invocation, result); } return result; }
ListenerInvokerWrapper执行invoke方法
@Override public Result invoke(Invocation invocation) throws RpcException { // 代码比较简单,没啥好说的 return invoker.invoke(invocation); }
AbstractInvoker执行invoke方法
@Override public Result invoke(Invocation inv) throws RpcException { // if invoker is destroyed due to address refresh from registry, let's allow the current invoke to proceed // 上面的注释是指,在调用过程中如果invoker被更新了,则打印一个warn,并允许当前调用继续执行 if (destroyed.get()) { logger.warn("Invoker for service " + this + " on consumer " + NetUtils.getLocalHost() + " is destroyed, " + ", dubbo version is " + Version.getVersion() + ", this invoker should not be used any longer"); } RpcInvocation invocation = (RpcInvocation) inv; invocation.setInvoker(this); // debug之后可以看到,attachment中存放的是接口信息 if (attachment != null && attachment.size() > 0) { invocation.addAttachmentsIfAbsent(attachment); } Map<String, String> contextAttachments = RpcContext.getContext().getAttachments(); if (contextAttachments != null && contextAttachments.size() != 0) { /** * invocation.addAttachmentsIfAbsent(context){@link RpcInvocation#addAttachmentsIfAbsent(Map)}should not be used here, * because the {@link RpcContext#setAttachment(String, String)} is passed in the Filter when the call is triggered * by the built-in retry mechanism of the Dubbo. The attachment to update RpcContext will no longer work, which is * a mistake in most cases (for example, through Filter to RpcContext output traceId and spanId and other information). */ invocation.addAttachments(contextAttachments); } // 获取本次调用是否是异步,如果是异步,则在invocation对象中设置该属性 if (getUrl().getMethodParameter(invocation.getMethodName(), Constants.ASYNC_KEY, false)) { invocation.setAttachment(Constants.ASYNC_KEY, Boolean.TRUE.toString()); } // 代码跟进去不难发现,如果是异步调用,会将INVOKE_ID加入到附件中一并发送至服务提供方,在返回时,才能用INVOKE_ID匹配request RpcUtils.attachInvocationIdIfAsync(getUrl(), invocation); try { // 发起调用(详见下文) return doInvoke(invocation); } catch (InvocationTargetException e) { // biz exception 调用异常处理 Throwable te = e.getTargetException(); if (te == null) { return new RpcResult(e); } else { if (te instanceof RpcException) { ((RpcException) te).setCode(RpcException.BIZ_EXCEPTION); } return new RpcResult(te); } } catch (RpcException e) { if (e.isBiz()) { return new RpcResult(e); } else { throw e; } } catch (Throwable e) { return new RpcResult(e); } }
DubboInvoker执行doInvoke方法
@Override protected Result doInvoke(final Invocation invocation) throws Throwable { RpcInvocation inv = (RpcInvocation) invocation; final String methodName = RpcUtils.getMethodName(invocation); // 设置调用信息 inv.setAttachment(Constants.PATH_KEY, getUrl().getPath()); inv.setAttachment(Constants.VERSION_KEY, version); // 获取客户端ExchangeClient信息(用来发送调用请求),包括url、client、refenceCount、ghostClientMap属性 // url:中包记录dubbo、该provider的详细信息(version,interface,心跳频率等等) // client:服务器的信息(消费者和提供者)、长连接维持心跳的schedule线程池,此时也能看出dubbo是用netty构建的长连接 ExchangeClient currentClient; if (clients.length == 1) { currentClient = clients[0]; } else { currentClient = clients[index.getAndIncrement() % clients.length]; } try { boolean isAsync = RpcUtils.isAsync(getUrl(), invocation);// 是否异步 boolean isOneway = RpcUtils.isOneway(getUrl(), invocation);// 该项配置是指,本次调用是否为单向调用 int timeout = getUrl().getMethodParameter(methodName, Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); if (isOneway) { boolean isSent = getUrl().getMethodParameter(methodName, Constants.SENT_KEY, false); currentClient.send(inv, isSent);// 如果是单向调用,则send,本次调用结束 RpcContext.getContext().setFuture(null); return new RpcResult(); } else if (isAsync) { ResponseFuture future = currentClient.request(inv, timeout); RpcContext.getContext().setFuture(new FutureAdapter<Object>(future)); return new RpcResult(); } else { RpcContext.getContext().setFuture(null); // 同步则request,并返回一个ResponseFuture对象,执行get获取响应对象result // 通过Condition.await()方法等待provider响应,待响应到达后,执行condition.signal()方法 // request代码详见下文 return (Result) currentClient.request(inv, timeout).get(); } } catch (TimeoutException e) { throw new RpcException(RpcException.TIMEOUT_EXCEPTION, "Invoke remote method timeout. method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } catch (RemotingException e) { throw new RpcException(RpcException.NETWORK_EXCEPTION, "Failed to invoke remote method: " + invocation.getMethodName() + ", provider: " + getUrl() + ", cause: " + e.getMessage(), e); } }
HeaderExchangeChannel执行request方法
@Override public ResponseFuture request(Object request, int timeout) throws RemotingException { // 如果该channel被关闭则抛异常 if (closed) { throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!"); } // create request. 创建request对象并作包装 Request req = new Request(); req.setVersion(Version.getProtocolVersion()); req.setTwoWay(true);// 设置为双向(本次调用需要有响应) req.setData(request); // 注册future,用于获取响应 DefaultFuture future = new DefaultFuture(channel, req, timeout); try { channel.send(req); } catch (RemotingException e) { future.cancel();// 发生异常则cancel throw e; } return future; }
NettyChannel执行send方法
@Override public void send(Object message, boolean sent) throws RemotingException { super.send(message, sent);// 判断该channel是否被关闭 boolean success = true; int timeout = 0; try { ChannelFuture future = channel.write(message);// 发送信息 if (sent) { // 获取超时时间,默认1s timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); success = future.await(timeout);// 等待响应 } Throwable cause = future.getCause();// 异常处理 if (cause != null) { throw cause; } } catch (Throwable e) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); } if (!success) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + "in timeout(" + timeout + "ms) limit"); } }
调用结束
总结一下,在整个 dubbo
消费者调用过程中,几个关键类很重要。
com.alibaba.dubbo.rpc.RpcInvocation
- 每一次调用都会被转化成该对象,并且在调用过程中逐渐丰富该对象,在上述的调用链中多处使用
setAttachments
方法来记录相关信息。 - 看源码,该类是实现
Serializable
接口的,并且在最后的HeaderExchangeChannel
发送request
时将该对象setData
中。
com.alibaba.dubbo.rpc.Invoker
(包含诸多子类) 每个provider
在将服务注册完成之后,都会在每个consumer
中生成这么一个invoker
对象,在上述跟踪代码时没少见到这个对象,几乎是贯穿整个调用链的,那么有什么作用呢?又是怎么设计的呢?
- 如果你仔细阅读过上述文章,应该不难发现,在各种
invoker
中跟代码时,总会时不时又出来另外一个invoker
,比如:DubboInvoker
、FailbackClusterInvoker
和MockClusterInvoker
(该类使用静态代理实现)等等。为什么呢?每个类中都各自的业务意义,比如是否使用mock
功能,比如挑选ExchangeClient
来进行发送操作,比如获取重试次数进行retryloop
。 - 仔细的小伙伴应该能在
AbstractClusterInvoker
类中看到有这么一段代码List<Invoker<T>>invokers=list(invocation);
,该invoker
其实是从directory
中获取(又一个重要的类,下文详细说明),那么又是怎么维护的?
com.alibaba.dubbo.rpc.cluster.Directory
(子类AbstractDirectory
、RegistryDirectory
) 个人认为这个类是整个dubbo
调用链中最为重要的类,里面承载了很多有用的信息。
RegistryDirectory
类中的methodInvokerMap
对象,该map中cache
了所有dubbo
协议中的service method
和invoker
对应信息,上文所说的获取invoker
就是从该map中获取的。AbstractDirectory
中的routers
对象,为dubbo
提供了路由保障,具体如果使用(后续再研究)- 还有
urlInvokerMap
、routerFactory
、configuratorFactory
等,这些属性如何使用读者自行看代码吧,本篇不作描述。
总结
Dubbo消费者侧的调用源码暂时也就到这了,希望能对读者有用,后续还会继续研究源码,了解最底层原理,看多了源码,自己写的也就好了,在设计程序时或多或少的也能借鉴一些,提升自己。