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

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

ztj100 2024-12-25 16:49 15 浏览 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模型

相关推荐

使用Python编写Ping监测程序(python 测验)

Ping是一种常用的网络诊断工具,它可以测试两台计算机之间的连通性;如果您需要监测某个IP地址的连通情况,可以使用Python编写一个Ping监测程序;本文将介绍如何使用Python编写Ping监测程...

批量ping!有了这个小工具,python再也香不了一点

号主:老杨丨11年资深网络工程师,更多网工提升干货,请关注公众号:网络工程师俱乐部下午好,我的网工朋友。在咱们网工的日常工作中,经常需要检测多个IP地址的连通性。不知道你是否也有这样的经历:对着电脑屏...

python之ping主机(python获取ping结果)

#coding=utf-8frompythonpingimportpingforiinrange(100,255):ip='192.168.1.'+...

网站安全提速秘籍!Nginx配置HTTPS+反向代理实战指南

太好了,你直接问到重点场景了:Nginx+HTTPS+反向代理,这个组合是现代Web架构中最常见的一种部署方式。咱们就从理论原理→实操配置→常见问题排查→高级玩法一层层剖开说,...

Vue开发中使用iframe(vue 使用iframe)

内容:iframe全屏显示...

Vue3项目实践-第五篇(改造登录页-Axios模拟请求数据)

本文将介绍以下内容:项目中的public目录和访问静态资源文件的方法使用json文件代替http模拟请求使用Axios直接访问json文件改造登录页,配合Axios进行登录请求,并...

Vue基础四——Vue-router配置子路由

我们上节课初步了解Vue-router的初步知识,也学会了基本的跳转,那我们这节课学习一下子菜单的路由方式,也叫子路由。子路由的情况一般用在一个页面有他的基础模版,然后它下面的页面都隶属于这个模版,只...

Vue3.0权限管理实现流程【实践】(vue权限管理系统教程)

作者:lxcan转发链接:https://segmentfault.com/a/1190000022431839一、整体思路...

swiper在vue中正确的使用方法(vue中如何使用swiper)

swiper是网页中非常强大的一款轮播插件,说是轮播插件都不恰当,因为它能做的事情太多了,swiper在vue下也是能用的,需要依赖专门的vue-swiper插件,因为vue是没有操作dom的逻辑的,...

Vue怎么实现权限管理?控制到按钮级别的权限怎么做?

在Vue项目中实现权限管理,尤其是控制到按钮级别的权限控制,通常包括以下几个方面:一、权限管理的层级划分...

【Vue3】保姆级毫无废话的进阶到实战教程 - 01

作为一个React、Vue双修选手,在Vue3逐渐稳定下来之后,是时候摸摸Vue3了。Vue3的变化不可谓不大,所以,本系列主要通过对Vue3中的一些BigChanges做...

Vue3开发极简入门(13):编程式导航路由

前面几节文章,写的都是配置路由。但是在实际项目中,下面这种路由导航的写法才是最常用的:比如登录页面,服务端校验成功后,跳转至系统功能页面;通过浏览器输入URL直接进入系统功能页面后,读取本地存储的To...

vue路由同页面重定向(vue路由重定向到外部url)

在Vue中,可以使用路由的重定向功能来实现同页面的重定向。首先,在路由配置文件(通常是`router/index.js`)中,定义一个新的路由,用于重定向到同一个页面。例如,我们可以定义一个名为`Re...

那个 Vue 的路由,路由是干什么用的?

在Vue里,路由就像“页面导航的指挥官”,专门负责管理页面(组件)的切换和显示逻辑。简单来说,它能让单页应用(SPA)像多页应用一样实现“不同URL对应不同页面”的效果,但整个过程不会刷新网页。一、路...

Vue3项目投屏功能开发!(vue投票功能)

最近接了个大屏项目,产品想在不同的显示器上展示大屏项目不同的页面,做出来的效果图大概长这样...

取消回复欢迎 发表评论: