《Akka学习笔记:ACTORS介绍》
《Akka学习笔记:Actor消息传递(1)》
《Akka学习笔记:Actor消息传递(2)》
《Akka学习笔记:日志》
《Akka学习笔记:测试Actors》
《Akka学习笔记:Actor消息处理-请求和响应(1) 》
《Akka学习笔记:Actor消息处理-请求和响应(2) 》
《Akka学习笔记:ActorSystem(配置)》
《Akka学习笔记:ActorSystem(调度)》
消息
我们在前面仅仅讨论了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也将会创建。让我们来看看这到底是什么:
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 from 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
原创文章版权归过往记忆大数据(过往记忆)所有,未经许可不得转载。
本文链接: 【Akka学习笔记:Actor消息传递(2)】(https://www.iteblog.com/archives/1157.html)



