您的位置:首页 > 其它

Akka学习笔记:Actor消息传递(2)

2015-01-18 20:26 393 查看

消息

   我们在前面仅仅讨论了ActorRef的QuoteRequest,并没有看到message的类!这里将介绍,代码如下:
package me.rerun.akkanotes.messaging.protocols

object TeacherProtocol{

case class QuoteRequest()
case class QuoteResponse(quoteString:String)

}
正如你说知,QuoteRequest是用来给TeacherActor发送消息的;而Actor将会用QuoteResponse来响应。

DISPATCHER AND A MAILBOX

   ActorRef取出消息并放到Dispatcher中。在这种模式下,当我们创建了ActorSystem 和ActorRef,Dispatcher和MailBox也将会创建。让我们来看看这到底是什么:


如果想及时了解Spark、Hadoop或者Hbase相关的文章,欢迎关注微信公共帐号:iteblog_hadoop

1、MailBox

   每个Actor都有一个MailBox(后面我们将看到一个特殊情况)。在我们之前的模型中,每个Teacher也有一个MailBox。Teacher需要检查MailBox并处理其中的message。MailBox中有个队列并以FIFO方式储存和处理消息。

2、Dispatcher

   Dispatcher做一些很有趣的事。从图中可以看到,Dispatcher好像只是仅仅将message从ActorRef 传递到MailBox中。但是在这背后有件很奇怪的事:Dispatcher 包装了一个 ExecutorService (ForkJoinPool 或者 ThreadPoolExecutor).它通过ExecutorService运行 MailBox。代码片段如下:
protected[akka] override def registerForExecution(mbox: Mailbox, ...): Boolean = {
...
try {
executorService execute mbox
...
}
什么?你说是你来运行Mailbox?是的,我们前面已经看到Mailbox的队列中持有所有的消息。用executorService 运行Mailbox也一样。Mailbox必须是一个线程。代码中有大量的Mailbox的声明和构造函数,代码片段如下:
private[akka] abstract class Mailbox(val messageQueue: MessageQueue)
extends SystemMessageQueue with Runnable

Teacher Actor





   当MailBox的run方法被运行,它将从队列中取出消息,并传递到Actor进行处理。该方法最终在你将消息tell到ActorRef 中的时候被调用,在目标Actor其实是个receive 方法。TeacherActor 是基本的类,并且拥有一系列的quote,很明显,receive 方法是用来处理消息的。代码片段如下:
package me.rerun.akkanotes.messaging.actormsg1

import scala.util.Random

import akka.actor.Actor
import me.rerun.akkanotes.messaging.protocols.TeacherProtocol._

/*
* Your Teacher Actor class.
*
* The class could use refinement by way of
* using ActorLogging which uses the EventBus of the Actor framework
* instead of the plain old System out
*
*/

class TeacherActor extends Actor {

val quotes = List(
"Moderation is for cowards",
"Anything worth doing is worth overdoing",
"The trouble is you think you have time",
"You never gonna know if you never even try")

def receive = {

case QuoteRequest => {

import util.Random

//Get a random Quote <span id="0_nwp" style="width: auto; height: auto; float: none;"><a id="0_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?rs=1&u=http%3A%2F%2Fwww%2Eiteblog%2Ecom%2Farchives%2F1157&p=baidu&c=news&n=10&t=tpclicked3_hc&q=56075110_cpr&k=from&k0=%BA%AF%CA%FD&kdi0=8&k1=from&kdi1=8&k2=%C9%F9%C3%F7&kdi2=8&sid=3e015b27b737017d&ch=0&tu=u1887734&jk=a4fb3426f22ead16&cf=29&fv=16&stid=9&urlid=0&luki=2&seller_id=1&di=128" target="_blank" mpid="0" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">from</span></a></span> the list and construct a response
val quoteResponse=QuoteResponse(quotes(Random.nextInt(quotes.size)))

println (quoteResponse)

}

}

}
 TeacherActor的receive只匹配一种消息:QuoteRequest ,receive方法主要做以下几件事:
  1、匹配QuoteRequest;
  2、从quotes中随机取出一个quote;
  3、构造一个QuoteResponse;
  4、在控制台打印QuoteResponse
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: