scala 如何通过名称获取 Akka 演员作为 ActorRef?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25966635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Akka actor by name as an ActorRef?
提问by Phil
In Akka I can create an actor as follows.
在 Akka 中,我可以创建一个演员,如下所示。
Akka.system(app).actorOf(Props(classOf[UnzipActor]), name="somename")
Then I am in a different class, how can I get this actor?
那我在不同的班级,我怎么才能得到这个演员?
I can get an ActorSelection
我可以得到一个 ActorSelection
lazy val unzip: ActorSelection =
Akka.system.actorSelection("user/" + "somename")
However, a ActorSelectionis not what I want; I want an ActorRef. How can I get a ActorRef?
但是,aActorSelection不是我想要的;我想要一个ActorRef. 我怎样才能得到一个ActorRef?
I want to have an ActorRefsince I wish to schedule a call to an ActorRefusing the scheduler.
我想要一个,ActorRef因为我希望使用调度程序安排一个呼叫ActorRef。
Akka.system(app).scheduler.schedule(
5 seconds, 60 seconds, mustBeActorRef, MessageCaseClass())
回答by Arnaud Gourlay
You can use the method resolveOneon an ActorSelection to get an ActorRef asynchronously.
您可以使用resolveOneActorSelection 上的方法异步获取 ActorRef。
implicit val timeout = Timeout(FiniteDuration(1, TimeUnit.SECONDS))
Akka.system.actorSelection("user/" + "somename").resolveOne().onComplete {
case Success(actorRef) => // logic with the actorRef
case Failure(ex) => Logger.warn("user/" + "somename" + " does not exist")
}
ref : http://doc.akka.io/api/akka/2.3.6/index.html#akka.actor.ActorSelection
参考:http: //doc.akka.io/api/akka/2.3.6/index.html#akka.actor.ActorSelection
回答by Chris Martin
Looking up Actors by Concrete Path:
To acquire an
ActorRefthat is bound to the life-cycle of a specific actor you need to send a message, such as the built-inIdentifymessage, to the actor and use thesender()reference of a reply from the actor.
要获取
ActorRef绑定到特定参与者生命周期的 ,您需要向参与者发送消息,例如内置Identify消息,并使用sender()参与者回复的引用。
But for the case you're describing, it might be more appropriate to use the scheduler to send a message to an ActorRefyou already have (like selfor a new temporary actor), and react to that message by sending a MessageCaseClassto actorSelection("user/somename").
但对于您所描述的情况下,可能更适合使用调度将消息发送到ActorRef你已经有(像self或新的临时演员),并通过发送该消息作出反应MessageCaseClass来actorSelection("user/somename")。

