本文主要是介绍actor 模型原理 (三),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
上面这个图呢,展示了老师这个actor收到消息之后,给学生回复的过程
DriverApp
发送一个初始化 InitSignal
消息给 StudentActor
StudentActor
收到这个消息之后给老师发了一个 QuoteRequest
老师 回复了一个 QuoteResponse
.学生收到之后再把这个回复打印出来
对于驱动程序,那么上面它做的事情用代码就是这样来做
//Initialize the ActorSystemval system = ActorSystem("UniversityMessageSystem")//construct the teacher actorval teacherRef = system.actorOf(Props[TeacherActor], "teacherActor")//construct the Student Actor - pass the teacher actorref as a constructor parameter to StudentActorval studentRef = system.actorOf(Props(new StudentActor(teacherRef)), "studentActor")//send a message to the Student ActorstudentRef ! InitSignal
按照我们的理解,就是直接创建一个学生actor的代理,然后发送消息给这个代理,但是学生actor的代理,需要老师actor的代理作为构造参数放进去,这种就是驱动模式
即我让某个actor发送某个请求给xxx, 比如你是学生家长,你要让你的孩子给老师打个电话,你丫的是不是得告诉学生老师的电话啊。
那么对于学生这个actor来说,它也是actor,收到的消息也是前面mailbox那一套机制,那么当它收到这个initsignal的时候,你需要在receive里面把要做的事情定义清楚
def receive = { case InitSignal=> {teacherActorRef!QuoteRequest}......
很简单,就是这样的代码
case QuoteResponse(quoteString) => { log.info ("Received QuoteResponse from Teacher")log.info(s"Printing from Student Actor $quoteString")
}
接收到的消息打印一下,也是放在receive方法里面
class TeacherActor extends Actor with ActorLogging {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 responseval quoteResponse = QuoteResponse(quotes(Random.nextInt(quotes.size)))//respond back to the Student who is the original sender of QuoteRequestsender ! quoteResponse}}
}
那么老师要回复消息怎么回复呢,使用sender,sender应该是Actor内置的一个成员,直接调用就可以了
这篇关于actor 模型原理 (三)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!