天天看點

Akka學習筆記:Actor消息傳遞(2)

文章目錄 [hide]

  • 1 消息
  • 2 DISPATCHER AND A MAILBOX
    • 2.1 1、MailBox
    • 2.2 2、Dispatcher
  • 3 Teacher Actor

消息

   我們在前面僅僅讨論了ActorRef的QuoteRequest,并沒有看到message的類!這裡将介紹,代碼如下:

1

package

me.rerun.akkanotes.messaging.protocols

2

3

object

TeacherProtocol{

4

5

case

class

QuoteRequest()

6

case

class

QuoteResponse(quoteString

:

String)

7

8

}

   正如你說知,QuoteRequest是用來給TeacherActor發送消息的;而Actor将會用QuoteResponse來響應。

DISPATCHER AND A MAILBOX

   ActorRef取出消息并放到Dispatcher中。在這種模式下,當我們建立了ActorSystem 和ActorRef,Dispatcher和MailBox也将會建立。讓我們來看看這到底是什麼:

Akka學習筆記:Actor消息傳遞(2)

如果想及時了解 Spark、Hadoop或者Hbase相關的文章,歡迎關注微信公共帳号: iteblog_hadoop

1、MailBox

   每個Actor都有一個MailBox(後面我們将看到一個特殊情況)。在我們之前的模型中,每個Teacher也有一個MailBox。Teacher需要檢查MailBox并處理其中的message。MailBox中有個隊列并以FIFO方式儲存和處理消息。

2、Dispatcher

   Dispatcher做一些很有趣的事。從圖中可以看到,Dispatcher好像隻是僅僅将message從ActorRef 傳遞到MailBox中。但是在這背後有件很奇怪的事:Dispatcher 包裝了一個 ExecutorService (ForkJoinPool 或者 ThreadPoolExecutor).它通過ExecutorService運作 MailBox。代碼片段如下:

1

protected

[akka] 

override

def

registerForExecution(mbox

:

Mailbox, ...)

:

Boolean 

=

2

...

3

try

{

4

executorService execute mbox

5

...

6

}

   什麼?你說是你來運作Mailbox?是的,我們前面已經看到Mailbox的隊列中持有所有的消息。用executorService 運作Mailbox也一樣。Mailbox必須是一個線程。代碼中有大量的Mailbox的聲明和構造函數,代碼片段如下:

1

private

[akka] 

abstract

class

Mailbox(

val

messageQueue

:

MessageQueue)

2

extends

SystemMessageQueue 

with

Runnable

Teacher Actor

Akka學習筆記:Actor消息傳遞(2)

如果想及時了解 Spark、Hadoop或者Hbase相關的文章,歡迎關注微信公共帳号: iteblog_hadoop

   當MailBox的run方法被運作,它将從隊列中取出消息,并傳遞到Actor進行處理。該方法最終在你将消息tell到ActorRef 中的時候被調用,在目标Actor其實是個receive 方法。TeacherActor 是基本的類,并且擁有一系列的quote,很明顯,receive 方法是用來處理消息的。代碼片段如下:

01

package

me.rerun.akkanotes.messaging.actormsg

1

02

03

import

scala.util.Random

04

05

import

akka.actor.Actor 

06

import

me.rerun.akkanotes.messaging.protocols.TeacherProtocol.

_

07

08

16

17

class

TeacherActor 

extends

Actor {

18

19

val

quotes 

=

List(

20

"Moderation is for cowards"

,

21

"Anything worth doing is worth overdoing"

,

22

"The trouble is you think you have time"

,

23

"You never gonna know if you never even try"

)

24

25

def

receive 

=

{

26

27

case

QuoteRequest 

=

> {

28

29

import

util.Random

30

31

//Get a random Quote from the list and construct a response

32

val

quoteResponse

=

QuoteResponse(quotes(Random.nextInt(quotes.size)))

33

34

println (quoteResponse)

35

36

}

37

38

}

39

40

}

  TeacherActor的receive隻比對一種消息:QuoteRequest ,receive方法主要做以下幾件事:

  1、比對QuoteRequest;

  2、從quotes中随機取出一個quote;

  3、構造一個QuoteResponse;

  4、在控制台列印QuoteResponse

繼續閱讀