Akka學習筆記 Actor訊息傳遞 2

2021-07-13 13:24:55 字數 3232 閱讀 2143

文章目錄 [hide]

3 teacher actor

我們在前面僅僅討論了actorref的quoterequest,並沒有看到message的類!這裡將介紹,**如下:

1packageme.rerun.akkanotes.messaging.protocols

2

3objectteacherprotocol

正如你說知,quoterequest是用來給teacheractor傳送訊息的;而actor將會用quoteresponse來響應。

actorref取出訊息並放到dispatcher中。在這種模式下,當我們建立了actorsystem 和actorref,dispatcher和mailbox也將會建立。讓我們來看看這到底是什麼:

如果想及時了解

sparkiteblog_hadoop

每個actor都有乙個mailbox(後面我們將看到乙個特殊情況)。在我們之前的模型中,每個teacher也有乙個mailbox。teacher需要檢查mailbox並處理其中的message。mailbox中有個佇列並以fifo方式儲存和處理訊息。

dispatcher做一些很有趣的事。從圖中可以看到,dispatcher好像只是僅僅將message從actorref 傳遞到mailbox中。但是在這背後有件很奇怪的事:dispatcher 包裝了乙個 executorservice (forkjoinpool 或者 threadpoolexecutor).它通過executorservice執行 mailbox。**片段如下:

1protected[akka]overridedefregisterforexecution(mbox:mailbox, ...):boolean=

什麼?你說是你來執行mailbox?是的,我們前面已經看到mailbox的佇列中持有所有的訊息。用executorservice 執行mailbox也一樣。mailbox必須是乙個執行緒。**中有大量的mailbox的宣告和建構函式,**片段如下:

1private[akka]abstractclassmailbox(valmessagequeue:messagequeue)

2extendssystemmessagequeuewithrunnable

如果想及時了解

sparkiteblog_hadoop

當mailbox的run方法被執行,它將從佇列中取出訊息,並傳遞到actor進行處理。該方法最終在你將訊息tell到actorref 中的時候被呼叫,在目標actor其實是個receive 方法。teacheractor 是基本的類,並且擁有一系列的quote,很明顯,receive 方法是用來處理訊息的。**片段如下:

01packageme.rerun.akkanotes.messaging.actormsg1

02

03importscala.util.random

04

05importakka.actor.actor

06importme.rerun.akkanotes.messaging.protocols.teacherprotocol._

07

08/*

09* your teacher actor class.

10*

11* the class could use refinement by way of

12* using actorlogging which uses the eventbus of the actor framework

13* instead of the plain old system out

14*

15*/

16

17classteacheractorextendsactor

37

38}

39

40}

teacheractor的receive只匹配一種訊息:quoterequest ,receive方法主要做以下幾件事:

1、匹配quoterequest;

2、從quotes中隨機取出乙個quote;

3、構造乙個quoteresponse;

4、在控制台列印quoteresponse

Akka學習筆記06 Actor的訊息

向actor傳送訊息,分為兩種方式 1.tell,或者使用符號 沒有返回值。寫法如下 actor msg or actor.tell msg or actor tell msg 如果需要指定傳送訊息的actor,可以寫成 actor.tell msg,anotheractorref 2.ask,或者...

翻譯 AKKA筆記 Actor訊息 1(二)

訊息 我們只是讓quoterequest到actorref去但是我們根本沒見過訊息類!它是這樣的 乙個最佳實踐是把你的訊息類包裝在乙個完整的物件裡以利於更好的組織 teacherprotocol package me.rerun.akkanotes.messaging.protocols objec...

Akka學習筆記(3) Actor

actor是akka中的核心概念,它為併發和分布式提供了一種更高階別的抽象,使併發程式設計更加容易。定義actor 定義乙個actor非常簡單 繼承actor,並提供receive方法即可。不帶構造引數的actor class myactor1 extends actor 帶構造引數的actor c...