[英]How to select akka actor with actorSelection?
我試圖選擇一個已經創建的actor。 這是一個代碼:
val myActor = system.actorOf(Props(classOf[MyActor]), "myActorName")
println("myActor path - " + akka.serialization.Serialization.serializedActorPath(myActor))
println("Selection from spec akka://unit-test/user/myActorName " + system.actorSelection("akka://unit-test/user/myActorName").resolveOne().value)
println("Selection from spec /user/myActorName/ " + system.actorSelection("/user/myActorName/").resolveOne().value)
結果是:
myActor path - akka.tcp://unit-test@127.0.0.1:46635/user/myActorName#1444872428
Selection from spec akka://unit-test/user/myActorName None
Selection from spec /user/myActorName/ None
我也可以向演員傳遞一個消息,它完成得很好。 我在actorSelection期間錯過了什么? 如何正確選擇演員?
更新
這很奇怪,但當我用system.actorSelection("/user/myActorName/").resolveOne().value
替換system.actorSelection("/user/myActorName/").resolveOne().value
system.actorFor("/user/myActorName/")
一切正常。 我的意思是actorFor
返回一個演員。 (由於不支持actorFor
這不是一個正確的解決方案)
請小心期貨。 在您的情況下,您收到的未來可能未在呼叫時刻完成 - 因此其值可能為空:
scala> println("Selection from spec /user/myActorName/ " + system.actorSelection("/user/myActorName/").resolveOne().value)
Selection from spec /user/myActorName/ None
VS
scala> val fut = system.actorSelection("/user/myActorName/").resolveOne()
fut: scala.concurrent.Future[akka.actor.ActorRef] = scala.concurrent.impl.Promise$DefaultPromise@7eb8d7bd
<just wait some time here>
scala> fut.value
res21: Option[scala.util.Try[akka.actor.ActorRef]] = Some(Success(Actor[akka://default/user/myActorName#1625966960]))
要正確獲取值,請使用onComplete或僅for
-comprehesion / map
:
import scala.concurrent.ExecutionContext.Implicits.global
for (res <- system.actorSelection("/user/myActorName").resolveOne()) {
println(res)
}
請記住,onComplete / for是作為偵聽器實現的,因此它們可能在不同的線程中執行。 如果你需要當前線程的結果 - 使用經典的Await.result
(它是阻塞的 - 所以,你應該在actor的context / receive
之外做)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.