路由引用路由器

时间:2014-08-19 13:42:35

标签: scala routing akka

如果我使用下面的代码(来自http://doc.akka.io/docs/akka/2.0/scala/routing.html),routees如何引用/ router2(不使用sender()),context.parent 1}}不起作用?

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)))

2 个答案:

答案 0 :(得分:1)

正如您目前所写的那样,他们无法做到。您必须明确地将路由器的ActorRef传递给路由器。

另一个选择是让路由器创建其路由,然后路由' context.parent将引用路由器。

答案 1 :(得分:0)

如果你真的希望一个白痴能够通过路由器与其他路由进行通信,那么你可以在创建所有内容后将路由器(引入它)作为消息发送到路由中。从那里,您可以通过路由器广播消息以将其发送到所有路由,但请记住,广播保证人也将收到相同的消息。像这样:

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")))
  }
}

然后,您的actor创建逻辑如下所示:

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))