2015-07-20 37 views
0

因此,當使用提問模式(actor ? msg)發送消息時,它會在幕後創建一個「one-off actor」。Akka - 使用提問模式的actorSelection

我的問題是 - 是否可以使用actorSelection發送此臨時演員消息?

例如,下面的代碼工作得很好:

object Test extends App { 

    case class WrappedMsg(msg: String, replyTo: ActorRef) 

    class Source(target: ActorRef) extends Actor { 
    def receive = { case _ => } // doesn't matter 

    implicit val execution = context.dispatcher 
    implicit val timeout = Timeout(5.seconds) 
    val middleware = context.actorOf(Props(new Middleware(target))) 
    (middleware ? "Something").mapTo[String].onComplete { 
     case Success(msg) => println("Success: " + msg) 
     case Failure(err) => println("Failure: " + err) 
    } 
    } 

    class Middleware(target: ActorRef) extends Actor { 
    def receive = { 
     case msg: String => 
     val wrappedMsg = WrappedMsg(replyTo = sender(), msg = msg) 
     target ! wrappedMsg 
    } 
    } 

    class Target extends Actor { 
    def receive = { 
     case wrappedMsg: WrappedMsg => wrappedMsg.replyTo ! "Received" 
    } 
    } 

    val system = ActorSystem() 
    val target = system.actorOf(Props(new Target)) 
    val source = system.actorOf(Props(new Source(target))) 

} 

但是,如果我做以下修改,以便使用演員網址,而不是ActorRef,它沒有:

case class WrappedMsg(msg: String, replyTo: String) 
... 
val wrappedMsg = WrappedMsg(replyTo = sender().path.toSerializationFormat, msg = msg) 
... 
case wrappedMsg: WrappedMsg => context.actorSelection(wrappedMsg.replyTo) ! "Received" 

謝謝

+0

「它失敗」是什麼意思? –

+0

「收到」消息未達到源(通過臨時參與者)。 在第一種情況下,打印「成功」,在第二種情況下打印「失敗」。 – AlonL

+0

'sender()。path.toSerializationFormat'返回'akka:// default/temp/$ a',順便說一句 – AlonL

回答

0

感謝@Zernike(請參閱問題中的評論),我們發現在Akka 2.3.12中效果很好 - 臨時演員使用actorSelection解決。 (導致故障的原始代碼在Akka 2.3.6中進行了測試)

-1

正如評論部分所述:toSerializationFormat返回一個形式爲「/ tmp/$ a」的字符串。

但是,context.actorSelection需要帶有actor路徑定位點的字符串。如documentation中所述的形式爲「akka:// my-sys/...」。

+0

對不起,錯誤信息。 'toSerializationFormat'(其結果是'context.actorSelection'得到的結果,返回'akka:// default/temp/$ a'。 我修正了以前的評論 – AlonL

+0

而btw,'actorSelection'沒有得到完整的演員路徑,但也是一個相對路徑,如文檔中所述 - http://doc.akka.io/docs/akka/snapshot/general/addressing.html#Absolute_vs__Relative_Paths – AlonL