[笔记迁移][Spark开发语言][Scala][13]多线程——Actor(了解)

版权声明:Collected by Bro_Rabbit only for study https://blog.csdn.net/weixin_38240095/article/details/84584110

Spark2.x的源码中,已经不在使用Actor进行消息通信,取而代之的是 RPCEndPoint,但用法、作用却是极为相似的 了解RPC

/**
 * An end point for the RPC that defines what functions to trigger given a message.
 *
 * It is guaranteed that `onStart`, `receive` and `onStop` will be called in sequence.
 *
 * The life-cycle of an endpoint is:
 *
 * {@code constructor -> onStart -> receive* -> onStop}
 *
 * Note: `receive` can be called concurrently. If you want `receive` to be thread-safe, please use
 * [[ThreadSafeRpcEndpoint]]
 *
 * If any error is thrown from one of [[RpcEndpoint]] methods except `onError`, `onError` will be
 * invoked with the cause. If `onError` throws an error, [[RpcEnv]] will ignore it.
 */
 private[spark] trait RpcEndpoint
  1. Actor类似Java中的多线程,但Scala的Actor使用不同的多线程模型,尽可能避免锁和共享状态,从而避免多线程并发时出现资源征用的情况以提高性能

  2. Spark 1.x使用Akka作为分布式多线程框架,Akaa实现了类似Scala Actor模型,其核心概念同样是Actor。2.11后Scala废弃了Actor,采用Akka做为默认

  3. Actor的创建、启动和消息收发
    (1) 实现Actor Trait, 重写act(),通过start()启动
    (2) 使用 “!” 向Actor发送消息
    (3) Actor内部使用receive()和模式匹配match接收消息
    (4) 案例 ActorHelloWorld

  4. 收发case class消息
    (1) Scala中,通常建议使用样例类,即case class来作为消息进行发送,然后在Actor接收消息之后,使用模式匹配对不同的消息进行处理
    (2)案例
    CaseClassMessage

  5. Actor之间互相收发消息
    (1) 一个Actor向另一个Actor发送消息时,同时带上自己的引用;其他Actor收到自己的消息时,直接通过收到的引用给发送方回复消息
    (2) 案例
    BetweenActors

  6. 同步消息和Future
    (1) 默认情况下,消息异步发送。如果希望同步发送,即对方接收后,一定要给自己返回结果,可以使用 “!?” 发送消息,即val reply = actor !? message
    (2) 若要异步发送一个消息,且后续要获得消息的返回值,可以使用Future,即 “!!”

    val future = actor !! message
    val reply = future()
    

猜你喜欢

转载自blog.csdn.net/weixin_38240095/article/details/84584110
今日推荐