如何通过名称验证 akka actor 是否存在

howto verify that akka actor exists by name

我正在尝试使用演员选择向演员发送消息。但它不断地变成死信。 这是创建演员的方式(使用激活器模板)

class PongActor extends Actor with ActorLogging {
  import PongActor._

  def receive = {
    case PingActor.PingMessage(text) => 
      log.info("In PongActor - received message: {}", text)
      sender() ! PongMessage("pong")
  } 
}

object PongActor {
  val props = Props[PongActor]
  case class PongMessage(text: String)
}

这是发送演员:

class PingActor extends Actor with ActorLogging {
  import PingActor._

  var counter = 0
  val pongActor = context.actorOf(PongActor.props, "pongActor")
val tester = context.actorSelection("../pongActor") //getting the actor by name using the actorSelection 
  def receive = {
    case Initialize => 
        log.info("In PingActor - starting ping-pong")
      tester.tell(PingMessage("ping"),self)//going to dead letters
      tester ! PingMessage("ping")//also going to dead letters 
    case PongActor.PongMessage(text) =>
      log.info("In PingActor - received message: {}", text)
      counter += 1
      if (counter == 3) context.system.shutdown()
      else sender() ! PingMessage("ping")
  } 
}

object PingActor {
  val props = Props[PingActor]
  case object Initialize
  case class PingMessage(text: String)
}
  1. 为什么邮件会变成死信

  2. 如何验证演员是否真的存在?

您的行 val tester = context.actorSelection("../pongActor") 是不必要的,因为上一行将 pongActor 设置为您需要的 actorRef。只需使用 pongActor.tellpongActor ! 而不是 tester.telltester !.

至于为什么 actorSelection 查找失败:当您在父 actor 中创建子 actor(这里 Ping 是父 actor,Pong 是子 actor),子路径与父路径相同,只是附加了子名称。因此,相对于 PingPong 的路径只是 "pongActor",而不是“../pongActor”。

来自 akka-docs

actorSelection only ever looks up existing actors when messages are delivered, i.e. does not create actors, or verify existence of actors when the selection is created.

更好的选择是使用 resolveOne

val timeout = 1.seconds
val tester1 = context.actorSelection("pongActor").resolveOne(timeout)