Spark如何使用Akka实现进程、节点通信的简明介绍


http://blog.csdn.net/beliefer/article/details/51056378


1.Akka简介

Scala认为Java线程通过共享数据以及通过锁来维护共享数据的一致性是糟糕的做法,容易引起锁的争用,而且线程的上下文切换会带来不少开销,降低并发程序的性能,甚至会引入死锁的问题。在Scala中只需要自定义类型继承Actor,并且提供act方法,就如同Java里实现Runnable接口,需要实现run方法一样。但是不能直接调用act方法,而是通过发送消息的方式(Scala发送消息是异步的),传递数据。如:

         Actor ! message

         Akka是Actor编程模型的高级类库,类似于JDK 1.5之后越来越丰富的并发工具包,简化了程序员并发编程的难度。Akka是一款提供了用于构建高并发的、分布式的、可伸缩的、基于Java虚拟机的消息驱动应用的工具集和运行时环境。从下面Akka官网提供的一段代码示例,可以看出Akka并发编程的简约。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. case class Greeting(who: String)  
  2. class GreetingActor extends Actor with ActorLogging {  
  3. def receive = {  
  4. case Greeting(who) ⇒ log.info("Hello " + who)  
  5.     }  
  6. }  
  7. val system = ActorSystem("MySystem")  
  8. val greeter = system.actorOf(Props[GreetingActor], name = "greeter")  
  9. greeter ! Greeting("Charlie Parker")  

Akka提供了分布式的框架,意味着用户不需要考虑如何实现分布式部署,Akka官网提供了下面的示例演示如何获取远程Actor的引用。
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. // config on all machines  
  2. akka {  
  3.  actor {  
  4.    provider = akka.remote.RemoteActorRefProvider  
  5.    deployment {  
  6.      /greeter {  
  7.        remote = akka.tcp://MySystem@machine1:2552  
  8.      }  
  9.    }  
  10.  }  
  11. }  
  12. // ------------------------------  
  13. // define the greeting actor and the greeting message  
  14. case class Greeting(who: String) extends Serializable  
  15. class GreetingActor extends Actor with ActorLogging {  
  16.   def receive = {  
  17.     case Greeting(who) ⇒ log.info("Hello " + who)  
  18.   }  
  19. }  
  20. // ------------------------------  
  21. // on machine 1: empty system, target for deployment from machine 2  
  22. val system = ActorSystem("MySystem")  
  23. // ------------------------------  
  24. // on machine 2: Remote Deployment - deploying on machine1  
  25. val system = ActorSystem("MySystem")  
  26. val greeter = system.actorOf(Props[GreetingActor], name = "greeter")  
  27. // ------------------------------  
  28. // on machine 3: Remote Lookup (logical home of “greeter” is machine2, remote deployment is transparent)  
  29. val system = ActorSystem("MySystem")  
  30. val greeter = system.actorSelection("akka.tcp://MySystem@machine2:2552/user/greeter")  
  31. greeter ! Greeting("Sonny Rollins")  
Actor之间最终会构成一棵树,作为父亲的Actor应当对所有儿子的异常失败进行处理(监管)Akka给出了简单的示例,代码如下。
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class Supervisor extends Actor {  
  2.   override val supervisorStrategy =  
  3.     OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {  
  4.       case _: ArithmeticException      ⇒ Resume  
  5.       case _: NullPointerException     ⇒ Restart  
  6.       case _: Exception                ⇒ Escalate  
  7.     }  
  8.   val worker = context.actorOf(Props[Worker])  
  9.   def receive = {  
  10.     case n: Int => worker forward n  
  11.   }  
  12. }  

Akka的更多信息请访问官方网站:http://akka.io/

基于Akka的分布式消息系统ActorSystem

         Spark使用Akka提供的消息系统实现并发:ActorSystem是Spark中最基础的设施,Spark既使用它发送分布式消息,又用它实现并发编程。正是因为Actor轻量级的并发编程、消息发送以及ActorSystem支持分布式消息发送等特点,Spark选择了ActorSystem。

         SparkEnv中创建ActorSystem时用到了AkkaUtils工具类,代码如下。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. val (actorSystem, boundPort) =  
  2.   Option(defaultActorSystem) match {  
  3.     case Some(as) => (as, port)  
  4.     case None =>  
  5.       val actorSystemName = if (isDriver) driverActorSystemName else executorActorSystemName  
  6.       AkkaUtils.createActorSystem(actorSystemName, hostname, port, conf, securityManager)  
  7.   }  

AkkaUtils.createActorSystem方法用于启动ActorSystem,代码如下。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. def createActorSystem(  
  2.     name: String,  
  3.     host: String,  
  4.     port: Int,  
  5.     conf: SparkConf,  
  6.     securityManager: SecurityManager): (ActorSystem, Int) = {  
  7.   val startService: Int => (ActorSystem, Int) = { actualPort =>  
  8.     doCreateActorSystem(name, host, actualPort, conf, securityManager)  
  9.   }  
  10.   Utils.startServiceOnPort(port, startService, conf, name)  
  11. }  

AkkaUtils使用了Utils的静态方法startServiceOnPort, startServiceOnPort最终会回调方法startService: Int=> (T, Int),此处的startService实际是方法doCreateActorSystem。真正启动ActorSystem是由doCreateActorSystem方法完成的,doCreateActorSystem的具体实现细节请见AkkaUtils的详细介绍。关于startServiceOnPort的实现,请参阅《Spark中常用工具类Utils的简明介绍》一文的内容。

AkkaUtils

AkkaUtils是Spark对Akka相关API的又一层封装,在介绍ActorSystem时,已经介绍了AkkaUtils的createActorSystem方法,这里对其它常用的功能进行介绍。

(1)doCreateActorSystem

功能描述:创建ActorSystem。
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1.   private def doCreateActorSystem(  
  2.       name: String,  
  3.       host: String,  
  4.       port: Int,  
  5.       conf: SparkConf,  
  6.       securityManager: SecurityManager): (ActorSystem, Int) = {  
  7.   
  8.   
  9.     val akkaThreads   = conf.getInt("spark.akka.threads"4)  
  10.     val akkaBatchSize = conf.getInt("spark.akka.batchSize"15)  
  11.     val akkaTimeout = conf.getInt("spark.akka.timeout"100)  
  12.     val akkaFrameSize = maxFrameSizeBytes(conf)  
  13.     val akkaLogLifecycleEvents = conf.getBoolean("spark.akka.logLifecycleEvents"false)  
  14.     val lifecycleEvents = if (akkaLogLifecycleEvents) "on" else "off"  
  15.     if (!akkaLogLifecycleEvents) {  
  16.       Option(Logger.getLogger("akka.remote.EndpointWriter")).map(l => l.setLevel(Level.FATAL))  
  17.     }  
  18.     val logAkkaConfig = if (conf.getBoolean("spark.akka.logAkkaConfig"false)) "on" else "off"  
  19.     val akkaHeartBeatPauses = conf.getInt("spark.akka.heartbeat.pauses"6000)  
  20.     val akkaFailureDetector =  
  21.       conf.getDouble("spark.akka.failure-detector.threshold"300.0)  
  22.     val akkaHeartBeatInterval = conf.getInt("spark.akka.heartbeat.interval"1000)  
  23. val secretKey = securityManager.getSecretKey()  
  24.     val isAuthOn = securityManager.isAuthenticationEnabled()  
  25.     if (isAuthOn && secretKey == null) {  
  26.       throw new Exception("Secret key is null with authentication on")  
  27.     }  
  28.     val requireCookie = if (isAuthOn) "on" else "off"  
  29.     val secureCookie = if (isAuthOn) secretKey else ""  
  30.     logDebug("In createActorSystem, requireCookie is: " + requireCookie)  
  31.     val akkaConf = ConfigFactory.parseMap(conf.getAkkaConf.toMap[String, String]).withFallback(  
  32.       ConfigFactory.parseString(  
  33.       s"""  
  34.       |akka.daemonic = on  
  35.       |akka.loggers = [""akka.event.slf4j.Slf4jLogger""]  
  36.       |akka.stdout-loglevel = "ERROR"  
  37.       |akka.jvm-exit-on-fatal-error = off  
  38.       |akka.remote.require-cookie = "$requireCookie"  
  39.       |akka.remote.secure-cookie = "$secureCookie"  
  40.       |akka.remote.transport-failure-detector.heartbeat-interval = $akkaHeartBeatInterval s  
  41.       |akka.remote.transport-failure-detector.acceptable-heartbeat-pause = $akkaHeartBeatPauses s  
  42.       |akka.remote.transport-failure-detector.threshold = $akkaFailureDetector  
  43.       |akka.actor.provider = "akka.remote.RemoteActorRefProvider"  
  44.       |akka.remote.netty.tcp.transport-class = "akka.remote.transport.netty.NettyTransport"  
  45.       |akka.remote.netty.tcp.hostname = "$host"  
  46.       |akka.remote.netty.tcp.port = $port  
  47.       |akka.remote.netty.tcp.tcp-nodelay = on  
  48.       |akka.remote.netty.tcp.connection-timeout = $akkaTimeout s  
  49.       |akka.remote.netty.tcp.maximum-frame-size = ${akkaFrameSize}B  
  50.       |akka.remote.netty.tcp.execution-pool-size = $akkaThreads  
  51.       |akka.actor.default-dispatcher.throughput = $akkaBatchSize  
  52.       |akka.log-config-on-start = $logAkkaConfig  
  53.       |akka.remote.log-remote-lifecycle-events = $lifecycleEvents  
  54.       |akka.log-dead-letters = $lifecycleEvents  
  55.       |akka.log-dead-letters-during-shutdown = $lifecycleEvents  
  56.       """.stripMargin))  
  57.     val actorSystem = ActorSystem(name, akkaConf)  
  58.     val provider = actorSystem.asInstanceOf[ExtendedActorSystem].provider  
  59.     val boundPort = provider.getDefaultAddress.port.get  
  60.     (actorSystem, boundPort)  
  61.   }  

(2)makeDriverRef

功能描述:从远端ActorSystem中查找已经注册的某个Actor。
[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. def makeDriverRef(name: String, conf: SparkConf, actorSystem: ActorSystem): ActorRef = {  
  2.   val driverActorSystemName = SparkEnv.driverActorSystemName  
  3.   val driverHost: String = conf.get("spark.driver.host""localhost")  
  4.   val driverPort: Int = conf.getInt("spark.driver.port"7077)  
  5.   Utils.checkHost(driverHost, "Expected hostname")  
  6.   val url = s"akka.tcp://$driverActorSystemName@$driverHost:$driverPort/user/$name"  
  7.   val timeout = AkkaUtils.lookupTimeout(conf)  
  8.   logInfo(s"Connecting to $name: $url")  
  9.   Await.result(actorSystem.actorSelection(url).resolveOne(timeout), timeout)  
  10. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值