Dubbo源码分析----发起请求

2024-08-30 09:58

本文主要是介绍Dubbo源码分析----发起请求,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

从如下代码中还是分析

String sayHello = demoService.sayHello("123123");

我们知道demoService实际上是一个代理对象,那么假设使用的是JDK的代码,看看获取代理的地方

public class JdkProxyFactory extends AbstractProxyFactory {@SuppressWarnings("unchecked")public <T> T getProxy(Invoker<T> invoker, Class<?>[] interfaces) {return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces,new InvokerInvocationHandler(invoker));}public <T> Invoker<T> getInvoker(T proxy, Class<T> type, URL url) {return new AbstractProxyInvoker<T>(proxy, type, url) {@Overrideprotected Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable {Method method = proxy.getClass().getMethod(methodName, parameterTypes);return method.invoke(proxy, arguments);}};}}

由动态代理的知识,可以知道代理对象调用方法的时候会经过InvocationHandler的invoke方法

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {String methodName = method.getName();Class<?>[] parameterTypes = method.getParameterTypes();//....return invoker.invoke(new RpcInvocation(method, args)).recreate();}

其中委托了invoker进行调用,这个invoker是什么呢? 要弄清楚这个问题,要回顾服务引用中的流程(com.alibaba.dubbo.config.ReferenceConfig#createProxy方法)

    private T createProxy(Map<String, String> map) {
//....if (urls.size() == 1) {invoker = refprotocol.refer(interfaceClass, urls.get(0));} else {//....if (registryURL != null) { URL u = registryURL.addParameter(Constants.CLUSTER_KEY, AvailableCluster.NAME); invoker = cluster.join(new StaticDirectory(u, invokers));}  else { invoker = cluster.join(new StaticDirectory(invokers));}}}// 创建服务代理return (T) proxyFactory.getProxy(invoker);}

主要是通过refprotocol.refer构造的invoker,从protocol的refer返回的是MockClusterInvoker,其装饰了FailoverClusterInvoker(默认,如果cluster配置了其他,则是其他实现),主要做mock用,忽略。
那么InvokerInvocationHandler中的invoker就是FailoverClusterInvoker,invoke方法会调用到FailoverClusterInvoker的doInvoke方法

    public Result doInvoke(Invocation invocation, final List<Invoker<T>> invokers, LoadBalance loadbalance) throws RpcException {//....从多个invoker中选出一个进行调用Result result = invoker.invoke(invocation);
//....return result;}

这时候的invoker结构如下:
image.png
第二层的invoker是ProtocolFilterWrapper的匿名内部类,其持有一个过滤器,这一层主要一层层调用,然后最后调用到DubboInvoker

public class DubboInvoker<T> extends AbstractInvoker<T> {@Overrideprotected 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 currentClient;// 获取连接Client对象,默认为1,可通过connections配置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);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);return (Result) currentClient.request(inv, timeout).get();}} catch () {//....}}
}

根据选择的模式分为3种:
1. 同步
2. 异步
3. 不需要返回值

同步

这种情况下,调用的是Client的request方法,底层是通过channel将请求发送出去

    public ResponseFuture request(Object request, int timeout) throws RemotingException {if (closed) {throw new RemotingException(this.getLocalAddress(), null, "Failed to send request " + request + ", cause: The channel " + this + " is closed!");}// create request.Request req = new Request();req.setVersion("2.0.0");req.setTwoWay(true);req.setData(request);DefaultFuture future = new DefaultFuture(channel, req, timeout);try{channel.send(req);}catch (RemotingException e) {future.cancel();throw e;}return future;}

由于是同步,而Netty发送是异步的,当时取不到返回结果,所以返回一个Future之后,需要等待结果返回,这时候调用的是get方法等待返回

异步

异步的情况和同步差不多,调用request方法发送请求得到future,返回放到RpcContext中,然后返回一个结果,使用如下:

            Future<Result> future = RpcContext.getContext().getFuture();result = future.get();

从源码上可以看出,如果同时异步调用了两个服务,那么后者的setFuture会覆盖前者的

不需要返回值

这种情况调用了send方法,底层类似,isSent表示是否等待消息发出

注意:
假设有这种情况,A–异步–>B–同步–>C
那么,A->B这种情况,会走上面异步的流程,因为配置了async属性,所以URL中存在这个属性,而当B->C,这个async属性被附带到B->C的调用附加参数中,导致走了异步的流程,但是其实应该是同步的
出现这种问题的原因如下,先看下A->B的时候,调用的ContextFilter

@Activate(group = Constants.PROVIDER, order = -10000)
public class ContextFilter implements Filter {public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {Map<String, String> attachments = invocation.getAttachments();if (attachments != null) {attachments = new HashMap<String, String>(attachments);attachments.remove(Constants.PATH_KEY);attachments.remove(Constants.GROUP_KEY);attachments.remove(Constants.VERSION_KEY);attachments.remove(Constants.DUBBO_VERSION_KEY);attachments.remove(Constants.TOKEN_KEY);attachments.remove(Constants.TIMEOUT_KEY);}RpcContext.getContext().setInvoker(invoker).setInvocation(invocation).setAttachments(attachments).setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort());//....}
}

这个invocation是A带过来的参数,那么attachments中自然有async=true的属性,而下面,会把attachments放到当前的RpcContext中

当B->C时,调用DubboInvoker方法前调用了AbstractInvoker的invoke方法

    public Result invoke(Invocation inv) throws RpcException {//....Map<String, String> context = RpcContext.getContext().getAttachments();if (context != null) {invocation.addAttachmentsIfAbsent(context);}//....}

这里,把context的attachments有设置回了invocation,导致B->C附带了async=true的属性

这篇关于Dubbo源码分析----发起请求的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1120493

相关文章

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Python主动抛出异常的各种用法和场景分析

《Python主动抛出异常的各种用法和场景分析》在Python中,我们不仅可以捕获和处理异常,还可以主动抛出异常,也就是以类的方式自定义错误的类型和提示信息,这在编程中非常有用,下面我将详细解释主动抛... 目录一、为什么要主动抛出异常?二、基本语法:raise关键字基本示例三、raise的多种用法1. 抛

github打不开的问题分析及解决

《github打不开的问题分析及解决》:本文主要介绍github打不开的问题分析及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、找到github.com域名解析的ip地址二、找到github.global.ssl.fastly.net网址解析的ip地址三

Mysql的主从同步/复制的原理分析

《Mysql的主从同步/复制的原理分析》:本文主要介绍Mysql的主从同步/复制的原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录为什么要主从同步?mysql主从同步架构有哪些?Mysql主从复制的原理/整体流程级联复制架构为什么好?Mysql主从复制注意

java -jar命令运行 jar包时运行外部依赖jar包的场景分析

《java-jar命令运行jar包时运行外部依赖jar包的场景分析》:本文主要介绍java-jar命令运行jar包时运行外部依赖jar包的场景分析,本文给大家介绍的非常详细,对大家的学习或工作... 目录Java -jar命令运行 jar包时如何运行外部依赖jar包场景:解决:方法一、启动参数添加: -Xb

Apache 高级配置实战之从连接保持到日志分析的完整指南

《Apache高级配置实战之从连接保持到日志分析的完整指南》本文带你从连接保持优化开始,一路走到访问控制和日志管理,最后用AWStats来分析网站数据,对Apache配置日志分析相关知识感兴趣的朋友... 目录Apache 高级配置实战:从连接保持到日志分析的完整指南前言 一、Apache 连接保持 - 性

python web 开发之Flask中间件与请求处理钩子的最佳实践

《pythonweb开发之Flask中间件与请求处理钩子的最佳实践》Flask作为轻量级Web框架,提供了灵活的请求处理机制,中间件和请求钩子允许开发者在请求处理的不同阶段插入自定义逻辑,实现诸如... 目录Flask中间件与请求处理钩子完全指南1. 引言2. 请求处理生命周期概述3. 请求钩子详解3.1

Linux中的more 和 less区别对比分析

《Linux中的more和less区别对比分析》在Linux/Unix系统中,more和less都是用于分页查看文本文件的命令,但less是more的增强版,功能更强大,:本文主要介绍Linu... 目录1. 基础功能对比2. 常用操作对比less 的操作3. 实际使用示例4. 为什么推荐 less?5.

spring-gateway filters添加自定义过滤器实现流程分析(可插拔)

《spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔)》:本文主要介绍spring-gatewayfilters添加自定义过滤器实现流程分析(可插拔),本文通过实例图... 目录需求背景需求拆解设计流程及作用域逻辑处理代码逻辑需求背景公司要求,通过公司网络代理访问的请求需要做请

Java集成Onlyoffice的示例代码及场景分析

《Java集成Onlyoffice的示例代码及场景分析》:本文主要介绍Java集成Onlyoffice的示例代码及场景分析,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 需求场景:实现文档的在线编辑,团队协作总结:两个接口 + 前端页面 + 配置项接口1:一个接口,将o