2015-11-08 40 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 
    } 

} 
相關問題