Scala Akka:如何更新“奴隶”演员的状态

王然|

我是Akka和Actor的新手,正在玩。为此,我使用一个父Actor和几个子actor,它们是从带有平衡池的路由器创建的。每个演员都会保存一些我想从父演员更新的数据(所有这些数据)。所以我做路由器之类的事情!广播(MessengeToAll(Somedata))

令我惊讶的是,在平衡池设置中,并非所有子actor的状态都被更新。我试图发送打印消息,发现我很愚蠢,因此当然没有必要全部更新,因为路由器似乎只是将消息发送到邮箱,而当我使用平衡池时,只有最空闲的参与者将“窃取”更新消息。

这可以通过使用RoundRobin路由器解决,但是,我仍然要使用Balancing Pool。我也不想要广播池。我在Scala文档中发现了有关事件总线的一些信息,但是它非常复杂,我真的不知道该怎么做。有人可以帮我一个(可能)简单的解决方案吗?非常感谢。:)

g

如果要向给定演员的所有子演员发送广播,则BalancingPool路由器绝对不是您想要的,RoundRobin路由器也不是。

阅读此链接中的“池与组”部分忽略它是.NET文档的事实;其内容与平台无关

如果使用路由池,则不会保留对由路由池创建的参与者的引用。因此,除非您想做一些魔术来找出角色路径名,否则只能使用该路由池的路由逻辑向他们发送消息。

您想要的是自己创建角色,然后在创建路由组时将其作为路由提供。然后,您可以直接或通过路由器对其进行寻址。

如果您想向他们发送所有消息,则只需myActors foreach (_ ! "message"),如果要通过路由器,则可以router ! "message"

恐怕没有等效的“ BalancingPool”路由器组。我将使用RoundRobin路由逻辑为您提供完整的示例:

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
>

祝您学习Akka好运!

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章