从 Akka 的上下文中获取演员的最佳方法是什么?

What is the best way to get an actor from the context in Akka?

我尝试了两种方式:

但我总觉得自己做错了什么。

我的演员代码:

def receive: Receive = {
  case "msg" ⇒ {

    ...

    val reader = Await.result(context.actorSelection("akka://Post/user/John").resolveOne(3 seconds), 10 seconds)
    reader ! data
  }
}

您应该永远不要在 Actor 的 receive 循环中阻塞 。充其量它会浪费资源,更糟糕的是它可能导致无法解决的死锁,因为线程池中的所有线程都已在使用中。

您的最佳选择是:

直接发送消息给actorSelection

您可以直接在演员选择上调用 tell。当然,你不知道解析是否成功。如果这种情况经常发生,肯定比让 actorRef 闲逛效率低。

context.actorSelection("akka://Post/user/John").resolveOne(3 seconds) ! data

异步解析选择

鉴于您手头有 Future,您可以在 onComplete 中发送您的消息或使用 pipeTo 将已解析的 ref 发送回您自己:

根据决议发送

def receive = {
  case data:Data =>
    context.actorSelection("akka://Post/user/John").resolveOne(3 seconds)
      .onComplete {
         case Success(reader) => reader ! data
         case Failure(e) => // handle failure
      }
}

管到自己

case class Deferred(data: Data, ref: ActorRef)

var johnRef: Option[ActorRef] = None

def receive = {
  case data:Data => johnRef match {
    case Some(reader) => reader ! data
    case None => context.actorSelection("akka://Post/user/John")
      .resolveOne(3 seconds)
      .map( reader => Deferred(data,reader)
      .pipeTo(self)

  case Deferred(data,ref) =>
    johnRef = Some(ref)
    ref ! data
}