斯卡拉阿卡:如何更新“奴隶”演员的状态

斯卡拉阿卡:如何更新“奴隶”演员的状态

问题描述:

我是阿卡和演员的新手,正在玩它。为此,我使用一个具有多个子actor的父Actor,这个子Actor是由具有平衡池的路由器创建的。每个演员将拥有一些我想要从父演员更新的数据(所有这些数据)。所以我做一些像 路由器!广播(MessengeToAll(Somedata))斯卡拉阿卡:如何更新“奴隶”演员的状态

令我惊讶的是,在平衡池设置中,并非所有儿童演员的状态都会更新。我试图发送一条打印消息,发现我很愚蠢,当然没有必要更新所有内容,因为路由器似乎只是向邮箱发送消息,而当我使用平衡池时,只有最懒惰的角色将“窃取”更新消息。

这可以通过使用RoundRobin路由器来解决,但是我仍然想使用平衡池。我也不想要一个广播池。我在斯卡拉发现了关于事件总线的一些东西,但它非常复杂,我不知道如何真正做到这一点。有人可以帮助我(可能)简单的解决方案吗?非常感谢。 :)

如果您想将广播发送给给定演员的所有子演员,则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

找到了〜谢谢〜 –