Akka - 使用askSelection和ask模式

时间:2015-07-20 11:47:27

标签: scala akka

因此,在使用询问模式(actor ? msg)发送消息时,它会在幕后创建“one-off actor”。

我的问题是 - 是否可以使用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)))

}

但是,如果我进行以下更改,为了使用actor url而不是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"

由于

2 个答案:

答案 0 :(得分:0)

感谢@Zernike(参见问题中的评论),我们发现在Akka 2.3.12中它运作良好 - 临时演员使用actorSelection解决。 (导致失败的原始代码在Akka 2.3.6中进行了测试)

答案 1 :(得分:-1)

如评论部分所述:toSerializationFormat返回“/ tmp / $ a”形式的字符串。

但是,context.actorSelection需要一个带有actor路径锚点的字符串。形式为“akka:// my-sys / ...”的内容,如documentation中所述。