Routees referring to Router

天大地大妈咪最大 提交于 2019-12-12 02:57:31

问题


If I use the code below (from http://doc.akka.io/docs/akka/2.0/scala/routing.html), how do the routees refer to/communicate with router2 (without using sender()), as the context.parent does not work?

val actor1 = system.actorOf(Props[ExampleActor1])
val actor2 = system.actorOf(Props[ExampleActor1])
val actor3 = system.actorOf(Props[ExampleActor1])
val routees = Vector[ActorRef](actor1, actor2, actor3)
val router2 = system.actorOf(Props[ExampleActor1].withRouter(
RoundRobinRouter(routees = routees)))

回答1:


As you've currently written it, they can't. You'll have to pass the router's ActorRef to the routees explicitly.

The other option is the let the router create its routees as then the routees' context.parent will refer to the router.




回答2:


If you really want a routee to be able to communicate with other routees over the router then you could send the router (introduce it) into the routees as a message after everything is created. From there, you can Broadcast a message over the router to get it to all routees, but keep in mind that the broadcasting routee will also receive the same message. Something like this:

object MyActor{
  case class SetParent(ref:ActorRef)
  case class OtherMessage(s:String)
} 

class MyActor extends Actor{
  import MyActor._

  def receive = myReceive()

  def myReceive(parentOpt:Option[ActorRef] = None):Receive = {
    case SetParent(parent) => context.become(myReceive(Some(parent)))
    case OtherMessage(msg) => println(s"Got other message: $msg")
    case someOtherMsg => 
      parentOpt foreach (parent => Broadcast(OtherMessage("hello world")))
  }
}

Then, your actor creation logic looks like this:

val actor1 = system.actorOf(Props[ExampleActor1])
val actor2 = system.actorOf(Props[ExampleActor1])
val actor3 = system.actorOf(Props[ExampleActor1])
val routees = Vector[ActorRef](actor1, actor2, actor3)
val router2 = system.actorOf(Props[ExampleActor1].withRouter(
  RoundRobinRouter(routees = routees)))
routees foreach (r => r ! SetParent(router))


来源:https://stackoverflow.com/questions/25384995/routees-referring-to-router

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!