因此,當使用提問模式(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"
謝謝
「它失敗」是什麼意思? –
「收到」消息未達到源(通過臨時參與者)。 在第一種情況下,打印「成功」,在第二種情況下打印「失敗」。 – AlonL
'sender()。path.toSerializationFormat'返回'akka:// default/temp/$ a',順便說一句 – AlonL