2015-07-20 77 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