百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

详解Flink组件通信——RPC协议 flink cep or

ztj100 2024-12-25 16:49 19 浏览 0 评论

Flink组件通讯过程

RPC(本地/远程)调用,底层是通过Akka提供的tell/ask方法进行通信。

Flink中RPC框架中涉及的主要类:


1、RpcGateway

Flink的RPC协议通过RpcGateway来定义,主要定义通信行为;用于远程调用RpcEndpoint的某些方法,可以理解为客服端代理。

若想与远端Actor通信,则必须提供地址(ip和port),如在Flink-on-Yarn模式下,JobMaster会先启动ActorSystem,此时TaskExecutor的Container还未分配,后面与TaskExecutor通信时,必须让其提供对应地址。

从类继承图可以看到基本上所有组件都实现了RpcGateway接口,其代码如下:

public interface RpcGateway {
/**
 * Returns the fully qualified address underwhich the associated rpc endpoint is reachable.
 *
 * @return Fully qualified (RPC) address underwhich the associated rpc endpoint is reachable
 */
String getAddress();
/**
 * Returns the fully qualified hostname underwhich the associated rpc endpoint is reachable.
 *
 * @return Fully qualified hostname under whichthe associated rpc endpoint is reachable
 */
String getHostname();
}

2、RpcEndpoint

RpcEndpoint是通信终端,提供RPC服务组件的生命周期管理(start、stop)。每个RpcEndpoint对应了一个路径(endpointId和actorSystem共同确定),每个路径对应一个Actor,其实现了RpcGateway接口,其构造函数如下:

protected RpcEndpoint(final RpcService rpcService, final String endpointId) {
// 保存rpcService和endpointId
this.rpcService =checkNotNull(rpcService, "rpcService");
this.endpointId =checkNotNull(endpointId, "endpointId");
// 通过RpcService启动RpcServer
this.rpcServer =rpcService.startServer(this);
// 主线程执行器,所有调用在主线程中串行执行
this.mainThreadExecutor= new MainThreadExecutor(rpcServer, this::validateRunsInMainThread);
}

构造的时候调用rpcService.startServer()启动RpcServer,进入可以接收处理请求的状态,最后将RpcServer绑定到主线程上真正执行起来。

在RpcEndpoint中还定义了一些方法如runAsync(Runnable)、callAsync(Callable, Time)方法来执行Rpc调用,值得注意的是在Flink的设计中,对于同一个Endpoint,所有的调用都运行在主线程,因此不会有并发问题,当启动RpcEndpoint/进行Rpc调用时,其会委托RcpServer进行处理。

3、RpcService和RpcServer

Akka有两种核心的异步通信方式:tell和ask。

RpcService 和 RpcServer是RpcEndPoint的成员变量。

1)RpcService 是Rpc服务的接口,其主要作用如下:

  • 根据提供的RpcEndpoint来启动和停止RpcServer(Actor);
  • 根据提供的地址连接到RpcServer,并返回一个RpcGateway;
  • 延迟/立刻调度Runnable、Callable;

在Flink中实现类为AkkaRpcService,是 Akka 的 ActorSystem 的封装,基本可以理解成 ActorSystem 的一个适配器。在ClusterEntrypoint(JobMaster)和TaskManagerRunner(TaskExecutor)启动的过程中初始化并启动。

AkkaRpcService中封装了ActorSystem,并保存了ActorRef到RpcEndpoint的映射关系。RpcService跟RpcGateway类似,也提供了获取地址和端口的方法。

在构造RpcEndpoint时会启动指定rpcEndpoint上的RpcServer,其会根据RpcEndpoint类型(FencedRpcEndpoint或其他)来创建不同的AkkaRpcActor(FencedAkkaRpcActor或AkkaRpcActor),并将RpcEndpoint和AkkaRpcActor对应的ActorRef保存起来,AkkaRpcActor是底层Akka调用的实际接收者,RPC的请求在客户端被封装成RpcInvocation对象,以Akka消息的形式发送。

最终使用动态代理将所有的消息转发到InvocationHandler,具体代码如下:

public <Cextends RpcEndpoint & RpcGateway> RpcServer startServer(C rpcEndpoint) {
... ...
// 生成RpcServer对象,而后对该server的调用都会进入Handler的invoke方法处理,handler实现了多个接口的方法
// 生成一个包含这些接口的代理,将调用转发到InvocationHandler
@SuppressWarnings("unchecked")
   RpcServerserver = (RpcServer) Proxy.newProxyInstance(
     classLoader,
     implementedRpcGateways.toArray(newClass<?>[implementedRpcGateways.size()]),
     akkaInvocationHandler);
return server;
}

2)RpcServer负责接收响应远端RPC消息请求。有两个实现:

  • AkkaInvocationHandler
  • FencedAkkaInvocationHandler

RpcServer的启动是通知底层的AkkaRpcActor切换为START状态,开始处理远程调用请求:

class AkkaInvocationHandler implements InvocationHandler, AkkaBasedEndpoint,RpcServer {
         @Override
         public void start() {
                  rpcEndpoint.tell(ControlMessages.START,ActorRef.noSender());
         }
}

4、AkkaRpcActor

AkkaRpcActor是Akka的具体实现,主要负责处理如下类型消息:

1)本地Rpc调用LocalRpcInvocation

会指派给RpcEndpoint进行处理,如果有响应结果,则将响应结果返还给Sender。

2)RunAsync & CallAsync

这类消息带有可执行的代码,直接在Actor的线程中执行。

3)控制消息ControlMessages

用来控制Actor行为,START启动,STOP停止,停止后收到的消息会丢弃掉。

5、RPC交互过程

RPC通信过程分为请求和响应。

1、 RPC请求发送

在RpcService中调用connect()方法与对端的RpcEndpoint建立连接,connect()方法根据给的地址返回InvocationHandler(AkkaInvocationHandler或FencedAkkaInvocationHandler,也就是RpcServer的实现)。

前面分析到客户端提供代理对象RpcServer,代理对象会调用AkkaInvocationHandler的invoke方法并传入RPC调用的方法和参数信息,代码如下:

AkkaInvocationHandler.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
 Class<?> declaringClass =method.getDeclaringClass();
 Object result;
// 判断方法所属的class
if(declaringClass.equals(AkkaBasedEndpoint.class) ||
 declaringClass.equals(Object.class) ||
 declaringClass.equals(RpcGateway.class) ||
 declaringClass.equals(StartStoppable.class) ||
 declaringClass.equals(MainThreadExecutable.class)||
 declaringClass.equals(RpcServer.class)) {
 result = method.invoke(this, args);
 } else if(declaringClass.equals(FencedRpcGateway.class)) {
throw new UnsupportedOperationException("AkkaInvocationHandler does not support thecall FencedRpcGateway#" +
 method.getName() + ". This indicates thatyou retrieved a FencedRpcGateway without specifying a " +
"fencingtoken. Please use RpcService#connect(RpcService, F, Time) with F being thefencing token to " +
"retrieve aproperly FencedRpcGateway.");
 } else {
 // rpc调用
 result = invokeRpc(method, args);
 }
return result;
}

代码中判断所属的类,如果是RPC方法,则调用invokeRpc方法。将方法调用封装为RPCInvocation消息。如果是本地则生成LocalRPCInvocation,本地消息不需要序列化,如果是远程调用则创建RemoteRPCInvocation。

判断远程方法调用是否需要等待结果,如果无需等待(void),则使用向Actor发送tell类型的消息,如果需要返回结果,则向Acrot发送ask类型的消息,代码如下:

AkkaInvocationHandler.java

private Object invokeRpc(Method method, Object[]args) throws Exception {
         String methodName = method.getName();
         Class<?>[] parameterTypes =method.getParameterTypes();
         Annotation[][] parameterAnnotations =method.getParameterAnnotations();
         Time futureTimeout =extractRpcTimeout(parameterAnnotations, args, timeout);
 
         final RpcInvocation rpcInvocation =createRpcInvocationMessage(methodName, parameterTypes, args);
 
         Class<?> returnType =method.getReturnType();
 
         final Object result;
 
         if (Objects.equals(returnType, Void.TYPE)) {
                  tell(rpcInvocation);
 
                  result = null;
         } else {
                  // Capture the call stack. Itis significantly faster to do that via an exception than
                  // via Thread.getStackTrace(),because exceptions lazily initialize the stack trace, initially only
                  // capture a lightweightnative pointer, and convert that into the stack trace lazily when needed.
                  final ThrowablecallStackCapture = captureAskCallStack ? new Throwable() : null;
 
                  // execute an asynchronouscall
                  // 异步调用等待返回
                  final CompletableFuture<?> resultFuture = ask(rpcInvocation, futureTimeout);
 
                  final CompletableFuture<Object> completableFuture = newCompletableFuture<>();
                  resultFuture.whenComplete((resultValue,failure) -> {
                          if (failure != null) {
                                   completableFuture.completeExceptionally(resolveTimeoutException(failure,callStackCapture, method));
                          } else {
                                   completableFuture.complete(deserializeValueIfNeeded(resultValue,method));
                          }
                  });
 
                  if (Objects.equals(returnType,CompletableFuture.class)) {
                          // 如果返回值是CompletableFuture类型,不用阻塞等待返回,直接返回Future对象
                          result =completableFuture;
                  } else {
                          try {
                                   // 如果返回值不是CompletableFuture类型,阻塞等待返回
                                   result = completableFuture.get(futureTimeout.getSize(),futureTimeout.getUnit());
                          } catch(ExecutionException ee) {
                                   throw new RpcException("Failure while obtaining synchronous RPC result.",ExceptionUtils.stripExecutionException(ee));
                          }
                  }
         }
 
         return result;
}

2、 RPC请求响应

RPC消息通过RpcEndpoint所绑定的Actor的ActorRef发送的,AkkaRpcActor是消息接收的入口,AkkaRpcActor在RpcEndpoint中构造生成,负责将消息交给不同的方法进行处理。

AkkaRpcActor.java

public Receive createReceive() {
         return ReceiveBuilder.create()
                  .match(RemoteHandshakeMessage.class,this::handleHandshakeMessage)
                  .match(ControlMessages.class,this::handleControlMessage)
                  .matchAny(this::handleMessage)
                  .build();
}

接收的消息有3种:

1)握手消息

在客户端构造时会通过ActorSelection发送过来。收到消息后检查接口、版本是否匹配。

AkkaRpcActor.java

private void handleHandshakeMessage(RemoteHandshakeMessagehandshakeMessage) {
         if(!isCompatibleVersion(handshakeMessage.getVersion())) {
                  // 版本不兼容异常处理
                  sendErrorIfSender(newAkkaHandshakeException(
                          String.format(
                                   "Versionmismatch between source (%s) and target (%s) rpc component. Please verify thatall components have the same version.",
                                   handshakeMessage.getVersion(),
                                   getVersion())));
         } else if(!isGatewaySupported(handshakeMessage.getRpcGateway())) {
                  // RpcGateway不匹配异常处理
                  sendErrorIfSender(newAkkaHandshakeException(
                          String.format(
                                   "The rpcendpoint does not support the gateway %s.",
                                   handshakeMessage.getRpcGateway().getSimpleName())));
         } else {
                  getSender().tell(new Status.Success(HandshakeSuccessMessage.INSTANCE),getSelf());
         }
}

2)控制消息

在RpcEndpoint调用start方法后,会向自身发送一条Processing.START消息来转换当前Actor的状态为STARTED,STOP也类似,并且只有在Actor状态为STARTED时才会处理RPC请求。

AkkaRpcActor.java

private void handleControlMessage(ControlMessages controlMessage) {
         try {
                  switch (controlMessage) {
                          case START:
                                   state =state.start(this);
                                   break;
                          case STOP:
                                   state =state.stop();
                                   break;
                          case TERMINATE:
                                   state =state.terminate(this);
                                   break;
                          default:
                                   handleUnknownControlMessage(controlMessage);
                  }
         } catch (Exception e) {
                  this.rpcEndpointTerminationResult= RpcEndpointTerminationResult.failure(e);
                  throw e;
         }
}

3)RPC消息

通过解析RpcInvocation获取方法名和参数类型,并从RpcEndpoint类中找到Method对象,通过反射调用该方法。如果有返回结果,会以Akka消息的形式发送回发送者。

AkkaRpcActor.java

private void handleMessage(final Object message) {
         if (state.isRunning()) {
                  mainThreadValidator.enterMainThread();
 
                  try {
                          handleRpcMessage(message);
                  } finally {
                          mainThreadValidator.exitMainThread();
                  }
         } else {
                  log.info("The rpcendpoint {} has not been started yet. Discarding message {} until processing isstarted.",
                          rpcEndpoint.getClass().getName(),
                          message.getClass().getName());
 
                  sendErrorIfSender(newAkkaRpcException(
                          String.format("Discardmessage, because the rpc endpoint %s has not been started yet.",rpcEndpoint.getAddress())));
         }
}

更多精彩内容:

Flink 流处理Api之Sink

一网打尽Flink高频面试题

大咖分享 | 通过制作一个迷你版Flink来学习Flink源码

用flink能替代spark的批处理功能吗

详解Flink通讯模型——Akka与Actor模型

相关推荐

Win10预览版10532已知问题汇总(微软win11正式版已知问题一览)

IT之家讯微软已向Insider用户推送了Win10预览版10532更新,本次更新对右键菜单、《Windows反馈》应用以及Edge浏览器进行了改进。除此之外还包含一些Bug,汇总如下,有意升级Wi...

Gabe Aul正测试Win10 Mobile 10532,Insider用户还需等

IT之家讯本月中旬微软向Insider用户推送了Win10Mobile预览版10512,该版本修复了一些Bug,增强了系统稳定性,但依然存在一些问题。今天,微软Insider项目负责人GabeAu...

微软开始推送Win10预览版10532快速版更新

8月28日消息,刚才,微软推送了Win10Build10532快速版,修复了之前的Bug,并带来了三项改进。主要来说,这次的更新改进了右键菜单的UI,使其更具Modern风格(见上图)。此外,更新...

Win10预览版10532更新内容大全(windows10更新预览版)

IT之家讯今天凌晨微软向Insider用户推送了Win10预览版10532快速版更新,本次更新主要带来了三处改进,汇总如下:o改进右键菜单,外观更加Modern。这是基于网友要求界面一致的反馈做出...

无法升级Win10预览版10532?也许Hyper-V在搞鬼

根据IT之家网友的反映,安装了微软虚拟机Hyper-V的Win10预览版用户无法成功升级Build10532版本,安装过程中会被要求回滚系统。很多朋友在尝试关闭虚拟机之后重启安装程序,结果仍然无法顺...

Win10预览版10532界面兴起“酷黑”风潮

Win10预览版10532的界面改动还是较为明显的,主要体现在右键菜单上面。总体来看,该版本的右键菜单间距更宽,视觉上更大气,操作上更便于触控。具体来说,任务栏右键菜单的变化最为明显。除了增加选项的宽...

Win10预览版10532上手图集(windows10预览版下载)

IT之家讯8月28日,微软今天推送了Win10预览版10532快速版更新,在该版本中,微软主要是加强细节上调整,并且主要是增强Edge浏览器性能等。在Windows10预览版10532中,微软改进了...

Win10预览版10532上手视频亮点演示

IT之家讯8月28日消息,今天凌晨微软向WindowsInsider快速通道用户推送了Win10预览版10532。在Windows10预览版10532中,微软改进了右键菜单,外观更加现代化。另外还...

第二篇 前端框架Vue.js(vue前端框架技术)

前端三大核心是网页开发的基础,Vue则是基于它们构建的“生产力工具”。通俗理解就是HTML是化妆的工具如眉笔,CSS是化妆品如口红,JavaScript是化妆后的互动,而Vue就是化妆助手。有了化妆工...

基于SpringBoot + vue2实现的旅游推荐管理系统

项目描述...

基于Vue以及iView组件的后端管理UI模板——iview-admin

介绍iView-admin是一套后端管理界面模板,基于Vue2.0,iView(现在为ViewUI)组件是一套完整的基于Vue的高质量组件库,虽然Github上有一套非常火的基于ElementUI...

别再说你会SPA开发了,这5个核心你真的搞懂了吗?

前言此spa非彼spa,不是你所熟知的spa。你所熟知的spa作者肯定是没有你熟悉的。我们这里指的是在前端开发中的一种模型,叫作单页应用程序,顾名思义,就是整个项目只有一个页面,而页面中的内容是动态的...

React.js Top20面试题(react.js中文官网)

概述作为React开发者,对框架的关键概念和原则有扎实的理解是很重要的。考虑到这一点,我整理了一份包含20个重要问题的清单,每个React开发者都应该知道,无论他们是在面试工作还是只是想提高技能。...

美媒:特朗普签署行政令后,FBI又发现约2400份、总计超14000页涉肯尼迪遇刺案文件

来源:环球时报新媒体1月23日特朗普下令公布肯尼迪遇刺案相关机密文件图源:美媒综合福克斯新闻网和Axios网站10日报道,在总统特朗普签署行政令,要求公布“肯尼迪遇刺案”相关政府机密文件之后,美国...

2021 年 Node.js 开发人员学习路线图

Node.js自发布以来,已成为业界重要破局者之一。Uber、Medium、PayPal和沃尔玛等大型企业,纷纷将技术栈转向Node.js。Node.js支持开发功能强大的应用,例如实时追踪...

取消回复欢迎 发表评论: