2016-05-06 114 views
1

我是阿卡和演員的新手,正在玩它。爲此,我使用一個具有多個子actor的父Actor,這個子Actor是由具有平衡池的路由器創建的。每個演員將擁有一些我想要從父演員更新的數據(所有這些數據)。所以我做一些像 路由器!廣播(MessengeToAll(Somedata))斯卡拉阿卡:如何更新「奴隸」演員的狀態

令我驚訝的是,在平衡池設置中,並非所有兒童演員的狀態都會更新。我試圖發送一條打印消息,發現我很愚蠢,當然沒有必要更新所有內容,因爲路由器似乎只是向郵箱發送消息,而當我使用平衡池時,只有最懶惰的角色將「竊取」更新消息。

這可以通過使用RoundRobin路由器來解決,但是我仍然想使用平衡池。我也不想要一個廣播池。我在斯卡拉發現了關於事件總線的一些東西,但它非常複雜,我不知道如何真正做到這一點。有人可以幫助我(可能)簡單的解決方案嗎?非常感謝。 :)

回答

1

如果您想將廣播發送給給定演員的所有子演員,則BalancingPool路由器絕對不是您想要的,也不是RoundRobin路由器。

閱讀this link中的「Pools vs Groups」部分。忽視它是.NET文檔的事實;其內容與平臺無關

如果使用路由池,則不保存對由路由池創建的參與者的引用。因此,除非您想要弄清演員路徑名,否則只能使用該路由池的路由邏輯向他們發送消息。

你想要的是自己創建演員,然後在創建路由組時提供它們作爲路由。然後你可以直接通過路由器來解決它們。

如果你想給他們所有的信息,你可以myActors foreach (_ ! "message"),如果你想通過路由器走,就可以router ! "message"

恐怕沒有「BalancingPool」路由器當量;我將使用循環路由邏輯給你一個完整的例子:

import akka.actor.{Actor, ActorSystem, Props} 
import akka.routing.{ActorRefRoutee, RoundRobinRoutingLogic, Router} 

import scala.concurrent.ExecutionContext.Implicits.global 
import scala.concurrent.Future 

class ParentActor extends Actor { 
    val actors = (1 to 5).map(i => context.system.actorOf(Props[ChildActor], "child" + i)) 
    val routees = actors map ActorRefRoutee 

    val router = Router(RoundRobinRoutingLogic(), routees) 

    router.route("hello", sender()) 
    router.route("hello", sender()) 
    router.route("hello", sender()) 
    router.route("hello", sender()) 
    router.route("hello", sender()) 

    actors foreach (_ ! "broadcast") 

    def receive = { case _ => } 
} 

class ChildActor extends Actor { 
    def receive = { 
    case "hello" => println(s"${self.path.name} answers hey") 
    case "broadcast" => println(s"${self.path.name} received broadcast") 
    } 
} 

object Main extends App { 
    val system = ActorSystem("HelloSystem") 

    val parent = system.actorOf(Props(classOf[ParentActor])) 

    Future { 
    Thread.sleep(5000) 
    system.terminate() 
    } 
} 

輸出時sbt run

[info] Running Main 
child2 answers hey 
child5 answers hey 
child1 answers hey 
child4 answers hey 
child1 received broadcast 
child3 answers hey 
child4 received broadcast 
child3 received broadcast 
child5 received broadcast 
child2 received broadcast 
[success] Total time: 8 s, completed 7/05/2016 6:28:18 PM 
> 

好運學習阿卡!

+0

這很好!我一直在考慮如何做很久〜 –

+0

對不起,我正試圖找到接受答案的地方........... –

+0

找到了〜謝謝〜 –