在前面的文章《Akka學習筆記:Actor消息傳遞(1)》和《Akka學習筆記:Actor消息傳遞(2)》。我們僅僅將消息發送到Actor,並沒有期待從Actor發來的響應。
從技術上講,我們給Actor發送消息,除了沒有響應,目標的Actor將對這條消息進行如下操作:
1、給發送者發送一個響應,在我們的例子中,TeacherActor將發送一個quote 到StudentActor作爲響應。或者
2、給其他的Actor響應,而這個Actor可能也會作出響應或者轉發等。Routers和Supervisors就是這個例子,我們將在後面看到。
請求和響應
這裏我們只研究場景1
如果想及時瞭解Spark、Hadoop或者Hbase相關的文章,歡迎關注微信公共帳號:iteblog_hadoop
上圖傳達了我們此刻想表達的意思。爲了簡單,我沒有在圖中畫出ActorSystem、Dispatcher 和Mailboxes。
1、DriverApp個StudentActor發送了一個InitSignal消息;
2、StudentActor對InitSignal消息作出反應,並且發送了QuoteRequest 消息給TeacherActor;
3、TeacherActor用QuoteResponse作出了響應;
4、StudentActor僅僅將QuoteResponse 作爲日誌打印到控制檯/logger。
我們將在testcase中進行確認。讓我們先來看看上面4點:
一、DriverApp個StudentActor發送了一個InitSignal消息
到現在爲止,你可能已經猜到了DriverApp將要做的事,僅僅4件事
1)、初始化ActorSystem
//Initialize the ActorSystem val system = ActorSystem("UniversityMessageSystem")
2)、創建TeacherActor
//create the teacher actor val teacherRef = system.actorOf(Props[TeacherActor], "teacherActor")
3)、創建StudentActor
//create the Student Actor - pass the teacher actorref //as a constructor parameter to StudentActor val studentRef = system.actorOf(Props(new StudentActor(teacherRef)), "studentActor")
你可能注意到,我用TeacherActor 作爲StudentActor構造參數,並傳入到ActorRef 中,這樣StudentActor 將可以用ActorRef發送消息到TeacherActor。還有其他的方法可以實現類似的功能(比如利用Props),但是當我們想查看 Supervisors 和Routers的時候,這個方法很方便。我們很快看到一個自Actors,但是在這裏的語義不對:Student創建Teacher聽起來很不好。不是嗎?
4)、最後,DriverApp將給StudentActor發送InitSignal。所以StudentActor可以給TeacherActor發送QuoteRequest 消息。
//send a message to the Student Actor studentRef ! InitSignal
這就是DriverClass所做的。完整的代碼如下
package me.rerun.akkanotes.messaging.requestresponse import akka.actor.ActorSystem import akka.actor.Props import me.rerun.akkanotes.messaging.protocols.StudentProtocol._ import akka.actor.ActorRef object DriverApp extends App { //Initialize the ActorSystem val system = ActorSystem("UniversityMessageSystem") //construct the teacher actor val teacherRef = system.actorOf(Props[TeacherActor], "teacherActor") //construct the Student Actor - pass the teacher actorref // as a constructor parameter to StudentActor val studentRef = system.actorOf(Props(new StudentActor(teacherRef)), "studentActor") //send a message to the Student Actor studentRef ! InitSignal //Let's wait for a couple of seconds before we shut down the system Thread.sleep(2000) //Shut down the ActorSystem. system.shutdown() }