失败后Akka actorSelection重新连接

时间:2013-10-08 15:21:43

标签: scala akka actor

我有一个演员,它监视另一个演员(它是远程的,因此无法直接引用)。它使用actorSelectionIdentify获取对actor的引用,然后监视生成的ActorRef。这很有效。

但是现在我想在另一个actor终止时自动重新连接,所以我重用了相同的actorSelection(Actor get在同一个位置实例化),但这次通过Identify的查找失败了永远。我不知道,为什么它工作,当演员已经在开始时实例化而不是,否则。

编辑: 什么是奇怪的是,在第一次连接之前存在关联错误,而在尝试重新连接时则没有,即使远程jvm完全终止。我刚刚注意到,如果您在失败后等待一分钟或更长时间,则会返回关联错误并再次成功连接。有没有办法配置它(它是一个缓存?)机制。

这是标准行为还是我弄错了?

如果我弄错了我的代码:

object ServerMonitor {
  case object Request
  case class Reply(ref: ActorRef)
}

class ServerMonitor(path: String) extends Actor with ActorLogging {
  import ServerMonitor._

  var server: Option[ActorRef] = None  
  var listeners: Set[ActorRef] = Set.empty

  def receive = {
    case ActorIdentity("server", Some(ref)) =>
      server = Some(ref)
      context.watch(ref)
      listeners.foreach(_ ! Reply(ref))
      listeners = Set.empty
      log.info(s"connected to the server at $path")

    case ActorIdentity("server", None) =>
      server = None
      log.warning(s"couldnt reach the server at $path")
      import context.dispatcher
      context.system.scheduler.scheduleOnce(1 second) {
        context.actorSelection(path) ! Identify("server")
      }

    case Terminated(ref) =>
      log.warning("server terminated")
      server = None
      context.actorSelection(path) ! Identify("server")

    case Request =>
      server.fold { 
        listeners += sender
      } { ref =>
        sender ! Reply(ref)
      }
  }

  override def preStart() {
    context.actorSelection(path) ! Identify("server")
  }
}

1 个答案:

答案 0 :(得分:3)

好的,我刚刚发现,问题是什么。有一个配置值:

# The length of time to gate an address whose name lookup has failed
# or has explicitly signalled that it will not accept connections
# (remote system is shutting down or the requesting system is quarantined).
# No connection attempts will be made to an address while it remains
# gated. Any messages sent to a gated address will be directed to dead
# letters instead. Name lookups are costly, and the time to recovery
# is typically large, therefore this setting should be a value in the
# order of seconds or minutes.
gate-invalid-addresses-for = 60 s

可以将其设置为低,以便在恢复远程系统后快速重新连接。即使考虑到上述原因,60年代对我来说似乎非常高。