Akka 路由器向工人发送消息

Akka routers to send messages to workers

我正在查看 Akka 文档中有关路由器的一些示例。

来自文档:

默认情况下,当路由发送消息时,它会隐式地将自己设置为发送者。

sender ! x // replies will go to this actor

但是,将路由器设置为发件人通常对路由很有用。例如,如果您想在路由器后面隐藏路由的详细信息,您可能希望将路由器设置为发送方。以下代码片段显示了如何将 parent 路由器设置为发送方。

sender.tell("reply", context.parent) // replies will go back to parent
sender.!("reply")(context.parent) // alternative syntax (beware of the parens!)

请注意,如果路由不是路由器的 children,则需要不同的代码,即如果它们是在创建路由器时提供的。

Link: http://doc.akka.io/docs/akka/2.2.3/scala/routing.html

我的问题是我写了一段代码,其中提供了路由,但它们不是 children。不出所料,上述方法不起作用。这里需要什么不同的代码?

你可能想在这里做的是让路由器将其 "self" ref 发送给每个路由,然后可以通过以下方式设置发件人:

sender.tell("reply", routerRef) // or
sender.!("reply")(routerRef)

您将需要确定一个适当的消息(可能只是一个 ActorRef,或者可能是一个建议使用的案例 class,例如:case class RouterRef(ref: ActorRef)),并让路由receive 方法能够接受这样的消息并存储它。一个例子可能是:

class MyRoutee(...) extends Actor with ActorLogging with ... {

  import context._

  def receive = init

  def init: Receive = LoggingReceive { // Initially waits for router ref (and/or any other initialisation info it needs to be fed with)
    case RouterRef(ref) => become(active(ref)) // Received the router ref - change behaviour
  }

  def active(routerRef: ActorRef): Receive = LoggingReceive {
    ... // Normal running mode - routerRef is available
  }

}