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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,463评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,868评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,213评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,666评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,759评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,725评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,716评论 3 415
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,484评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,928评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,233评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,393评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,073评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,718评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,308评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,538评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,338评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,260评论 2 352

推荐阅读更多精彩内容