【问题标题】:howto verify that akka actor exists by name如何通过名称验证 akka 演员是否存在
【发布时间】:2015-11-13 05:02:07
【问题描述】:

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

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. 如何验证演员确实存在?

【问题讨论】:

    标签: scala akka


    【解决方案1】:

    来自akka-文档

    actorSelection 仅在传递消息时查找现有的参与者,即不创建参与者,或在创建选择时验证参与者的存在。

    更好的选择是使用resolveOne

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

    【讨论】:

    • 只是一个更正。在上面示例的上下文中,它应该是 val tester1 = context.actorSelection("pongActor").resolveOne(timeout)
    【解决方案2】:

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

    至于actorSelection查找失败的原因:当你在父actor内部创建子actor时(这里Ping是父actor,Pong是子actor),子actor的路径与父路径,附加了孩子的名字。所以,相对于PingPong 的路径只是“pongActor”,而不是“../pongActor”。

    【讨论】:

    • 谢谢。至于你答案的第一部分。我特意想检查 actorSelection 的使用作为演示。至于第二部分-非常有帮助-谢谢!!!
    猜你喜欢
    • 2013-08-03
    • 1970-01-01
    • 2014-05-15
    • 2014-11-15
    • 1970-01-01
    • 2018-04-27
    • 2018-06-15
    • 1970-01-01
    • 2013-11-22
    相关资源
    最近更新 更多