2015-11-08 97 views
0

我在查看Akka文档中的路由器的一些例子。阿卡路由器发送消息给工作人员

从文档:

默认情况下,当一个routee发送消息时,它会隐式设置本身作为发件人。

sender ! x // replies will go to this actor 

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

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

注意,将需要不同的代码,如果,如果他们在创建路由器时被提供的routees不是路由器,即儿童。

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

我的问题是我已经写了在那里提供的routees代码,他们还没有孩子。正如所料,上述方法不起作用。这里需要什么不同的代码?

回答

1

,你可能会想在这里做的是有路由器发送它的“自我”裁判各routees,然后可以通过设置发件人:

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

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

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 
    } 

}