Akka Notes - Actor Messaging - 1

In this first part of Actor Messaging, we'll create the Teacher Actor and instead of the Student Actor, we'll use a main program called StudentSimulatorApp.

Revisiting Student-Teacher in Detail

Let's for now consider the message sent by the StudentSimulatorApp to the TeacherActor alone. When I say StudentSimulatorApp, I just mean a normal main program.

TeacherRequestFlowSimulatedApp.png

The picture conveys this :
(if the terms are overwhelming, don't worry, we'll go through them in detail)

  • Student creates something called an ActorSystem
  • It uses the ActorSystem to create something called as ActorRef. The QuoteRequest
    message is sent to the ActorRef (a proxy to TeacherActor)
  • Actor ref passes the message along to a Dispatcher
  • The Dispatcher enqueues the message in the target Actor's MailBox.
  • The Dispatcher then puts the Mailbox on a Thread (more on that in the next section).
  • The MailBox dequeues a message and eventually delegates that to the actual Teacher Actor's receive method.

Like I said, don't worry about it. Let's look at each step in detail now. You can come back and revisit these five steps once we are done.

The StudentSimulatorApp program

We would use this StudentSimulatorApp to bring up the JVM and initialize the ActorSystem.

StudentSimulatorApp.png

As we understand from the picture, the StudentSimulatorApp

  • Creates an ActorSystem
  • Uses the ActorSystem to create a proxy to the Teacher Actor (ActorRef)
  • Sends the QuoteRequest message to the proxy.

Let's focus on these three points alone now.

1. Creating an ActorSystem

ActorSystem is the entry point into the ActorWorld. ActorSystems are through which you could create and stop Actors. Or even shutdown the entire Actor environment.
On the other end of the spectrum, Actors are hierarchical and the ActorSystem is also similar to the java.lang.Object or scala.Any for all Actors - meaning, it is the root for all Actors. When you create an Actor using the ActorSystem's actorOf method, you create an Actor just below the ActorSystem.

ActorSystemActorCreation.png

The code for initializing the ActorSystem looks like

val system=ActorSystem("UniversityMessageSystem")

The UniversityMessageSystem is simply a cute name you give to your ActorSystem.

2. Creating a Proxy for TeacherActor?

Let's consider the following snippet :

val teacherActorRef:ActorRef=actorSystem.actorOf(Props[TeacherActor])

The actorOf is the Actor creation method in ActorSystem. But, as you can see, it doesn't return a TeacherActor which we need. It returns something of type ActorRef.
The ActorRef acts as a Proxy for the actual Actors. The clients do not talk directly with the Actor. This is Actor Model's way of avoiding direct access to any custom/private methods or variables in the TeacherActor or any Actor for that sake.
To repeat, you send messages only to the ActorRef and it eventually reaches your actual Actor. You can NEVER talk to your Actor directly. People will hate you to death if you find some mean ways to do that.

ActorRef.png

3. Send aQuoteRequest to the Proxy

It's an one liner again. You just tell the QuoteRequest message to the ActorRef. The tell method in Actor is actually !. (there's also a tell method in ActorRef which just delegates the call back to !)

//send a message to the Teacher Actor 
teacherActorRef!QuoteRequest

That's it !!!
If you think I am lying, check the entire code of the StudentSimulatorApp below :

StudentSimulatorApp.scala

package me.rerun.akkanotes.messaging.actormsg1
import akka.actor.ActorSystem 
import akka.actor.Props 
import akka.actor.actorRef2Scala 
import me.rerun.akkanotes.messaging.protocols.TeacherProtocol._

object StudentSimulatorApp extends App{  
    //Initialize the ActorSystem 
    val    actorSystem=ActorSystem("UniversityMessageSystem")  
    //construct the Teacher Actor Ref 
    val teacherActorRef=actorSystem.actorOf(Props[TeacherActor])  
   //send a message to the Teacher Actor 
   teacherActorRef!QuoteRequest  
   //Let's wait for a couple of seconds before we shut down the system 
   Thread.sleep (2000)  
   //Shut down the ActorSystem. 
   actorSystem.shutdown()
} 

Well, I cheated a little. You'll have to shutdown the ActorSystem or otherwise, the JVM keeps running forever. And I am making the main thread sleep for a little while just to give the TeacherActor to finish off it's task. I know this sounds stupid. Don't worry about it. We'll write some neat testcases in the next part in order to avoid this hack.

The Message

We just told a QuoteRequest to the ActorRef but we didn't see the message class at all !!
Here it comes :

(It is a recommended practice to wrap your messages in a nice object for easier organization)

TeacherProtocol

package me.rerun.akkanotes.messaging.protocols
object TeacherProtocol{ 
    case class QuoteRequest() 
    case class QuoteResponse(quoteString:String)
}

As you know, the QuoteRequest is for the requests that come to the TeacherActor. The Actor would respond back with a QuoteResponse.

Dispatcher and a MailBox

The ActorRef delegates the message handling functionality to the Dispatcher. Under the hood, while we created the ActorSystem and the ActorRef , a Dispatcher and a MailBox was created. Let's see what they are about.

MessageDispatcherMailbox.png

MailBox

Ever Actor has one MailBox (we'll see one special case later). Per our analogy, every Teacher has one mailbox too. The Teacher has to check the mailbox and process the message. In Actor world, it's the other way round - the mailbox, when it gets a chance uses the Actor to accomplish its work.
Also the mailbox has a queue to store and process the messages in a FIFO fashion - a little different from our regular inbox where the most latest is the one at the top.

Now, the dispatcher

Dispatcher does some really cool stuff. From the looks of it, the Dispatcher just gets the message from the ActorRef and passes it on to the MailBox. But there's one amazing thing happening behind
the scenes :
The Dispatcher wraps an ExecutorService (ForkJoinPool or ThreadPoolExecutor). It executes the MailBox against this ExecutorService.
Check out this snippet from the Dispatcher

protected[akka] override def registerForExecution(mbox: Mailbox, ...): Boolean = { 
    ... try { 
                 executorService execute mbox ...
  }

What? Did you just say you execute the MailBox?

Yup. We already saw that the MailBox holds all the messages in a Queue. Also since the Executor runs the MailBox, the MailBox must be a Thread. You're right. That's pretty much MailBox's declaration and constructor.
Here's the signature of the Mailbox

private[akka] abstract class Mailbox(val messageQueue: MessageQueue) extends SystemMessageQueue with Runnable

Teacher Actor

TeacherActor.png

The MailBox, when it gets its run method fired, dequeues a message from the message queue and passes it to the Actor for processing.
The method that eventually gets called when you tell a message to an ActorRef is the receive
method of the target Actor.
The TeacherActor is a rudimentary class which has a List of quotes and obviously the receive
method which handles the messages.
Check this out :

TeacherActor.scala

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)
    }
  }
}

The TeacherActor's receive method pattern matches for just one Message - the QuoteRequest (actually, it is a good practice to pattern match the default case but there's an interesting story to tell there)
All that the receive method does is to

  • pattern match for QuoteRequest
  • pick a random quote from the static list of quotes
  • construct a QuoteResponse
  • print the QuoteResponse to the console
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末江耀,一起剝皮案震驚了整個(gè)濱河市斯撮,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌遣铝,老刑警劉巖球切,帶你破解...
    沈念sama閱讀 211,948評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件疯潭,死亡現(xiàn)場(chǎng)離奇詭異嘱根,居然都是意外死亡嚣潜,警方通過查閱死者的電腦和手機(jī)唤锉,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,371評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門世囊,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人窿祥,你說我怎么就攤上這事茸习。” “怎么了壁肋?”我有些...
    開封第一講書人閱讀 157,490評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵号胚,是天一觀的道長(zhǎng)籽慢。 經(jīng)常有香客問我,道長(zhǎng)猫胁,這世上最難降的妖魔是什么箱亿? 我笑而不...
    開封第一講書人閱讀 56,521評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮弃秆,結(jié)果婚禮上届惋,老公的妹妹穿的比我還像新娘。我一直安慰自己菠赚,他們只是感情好脑豹,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,627評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著衡查,像睡著了一般瘩欺。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上拌牲,一...
    開封第一講書人閱讀 49,842評(píng)論 1 290
  • 那天俱饿,我揣著相機(jī)與錄音,去河邊找鬼塌忽。 笑死拍埠,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的土居。 我是一名探鬼主播枣购,決...
    沈念sama閱讀 38,997評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼擦耀!你這毒婦竟也來了棉圈?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,741評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤埂奈,失蹤者是張志新(化名)和其女友劉穎迄损,沒想到半個(gè)月后定躏,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體账磺,經(jīng)...
    沈念sama閱讀 44,203評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,534評(píng)論 2 327
  • 正文 我和宋清朗相戀三年痊远,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了垮抗。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,673評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡碧聪,死狀恐怖冒版,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情逞姿,我是刑警寧澤辞嗡,帶...
    沈念sama閱讀 34,339評(píng)論 4 330
  • 正文 年R本政府宣布捆等,位于F島的核電站,受9級(jí)特大地震影響续室,放射性物質(zhì)發(fā)生泄漏栋烤。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,955評(píng)論 3 313
  • 文/蒙蒙 一挺狰、第九天 我趴在偏房一處隱蔽的房頂上張望明郭。 院中可真熱鬧,春花似錦丰泊、人聲如沸薯定。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,770評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)话侄。三九已至,卻和暖如春苛败,著一層夾襖步出監(jiān)牢的瞬間满葛,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,000評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工罢屈, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留嘀韧,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,394評(píng)論 2 360
  • 正文 我出身青樓缠捌,卻偏偏與公主長(zhǎng)得像锄贷,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子曼月,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,562評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容