Dubbo3.0最新源码分析:protocol 远程调用层

415 阅读2分钟

protocol 远程调用层:封装 RPC 调用,以 InvocationResult 为中心,扩展接口为 ProtocolInvokerExporter

「这是我参与2022首次更文挑战的第1天,活动详情查看:2022首次更文挑战

在 RPC 中,Protocol 是核心层,也就是只要有 Protocol + Invoker + Exporter 就可以完成非透明的 RPC 调用,然后在 Invoker 的主过程上 Filter 拦截点。

主要接口

Node接口 (API/SPI, Prototype, ThreadSafe)

  • 获取URL
URL getUrl();
  • 是否可用
boolean isAvailable();
  • 摧毁
void destroy();

Invoker接口 (API/SPI, Prototype, ThreadSafe)

实体域,它是 Dubbo 的核心模型,其它模型都向它靠扰,或转换成它,它代表一个可执行体,可向它发起 invoke 调用,它有可能是一个本地的实现,也可能是一个远程的实现,也可能一个集群实现。

  • 获取服务接口
Class<T> getInterface();
  • 调用
Result invoke(Invocation invocation) throws RpcException;
  • 销毁所有

Exporter接口 (API/SPI, Prototype, ThreadSafe)

  • 获得Invoker
Invoker<T> getInvoker();
  • 不暴露
void unexport();

Protocol接口 (API/SPI, Singleton, ThreadSafe)

被SPI注解的接口。服务域,它是 Invoker 暴露和引用的主功能入口,它负责 Invoker 的生命周期管理

  • 定义协议端口号
int getDefaultPort();
  • 暴露服务以进行远程调用
    1. Protoco接收请求后应记录请求源地址:
    RpcContext.getServerAttachment().setRemoteAddress();
    
    1. export()必须是幂等的,也就是说,调用一次和调用两次相同的URL之间没有区别
    2. Invoker程序实例是由framework传入的,protocol不需要在意
@Adaptive
<T> Exporter<T> export(Invoker<T> invoker) throws RpcException;
  • 引用远程服务
    1. 当用户调用从'refer()'返回的'Invoker'对象的'invoke()'方法时,协议需要相应执行'Invoker'对象的'invoke()'方法。
    2. 协议的职责是实现从'refer()'返回的'Invoker'。一般来说,协议发送远程请求在'Invoker'实现。
@Adaptive
<T> Invoker<T> refer(Class<T> type, URL url) throws RpcException;
  • 销毁协议
void destroy();

Invocation接口 (API, Prototype, NonThreadSafe)

会话域,它持有调用过程中的变量,比如方法名,参数等

  • 获取当前上下文的invoker
Invoker<?> getInvoker();
  • 获取方法名
String getMethodName();
  • 获取接口名
String getServiceName();

Result接口 (API, Prototype, NonThreadSafe)

调用的结果信息,主要的实现为:

  1. AsyncRpcResult
  2. AppResponse

Filter接口 (SPI, Singleton, ThreadSafe)

被SPI注解的接口。

* 从3.0开始, 消费者端的Filter已经被重构了. 在RPC请求的不同阶段有两种不同的工作机制。
* 1. Filter. 在实例级工作,每个Filter被绑定到一个特定的Provider实例(invoker).
* 2. ClusterFilter. 3.0中新引入的,在Loadbalancer选择一个特定的Filter之前拦截请求(Invoker).
*
*
* Filter Chain in 3.x
*
*                                          -> Filter -> Invoker
*
* Proxy -> ClusterFilter -> ClusterInvoker -> Filter -> Invoker
*
*                                          -> Filter -> Invoker
*
*
* Filter Chain in 2.x
*
*                            Filter -> Invoker
*
* Proxy -> ClusterInvoker -> Filter -> Invoker
*
*                            Filter -> Invoker

过滤器的实现

Protocol-ProtocolFilterWrapper

BaseFilter-Filter

FilterChainBuilder-DefaultFilterChainBuilder

以Triple协议的实现为例