Akka SupervisorStrategies 与 children 的关系

Relationship of Akka SupervisorStrategies to children

Java API 这里。我想了解 Akka actor 监督是如何工作的,特别是监督策略。对我来说,策略感觉就像它只是(本质上)将异常映射到指令。

我刚刚阅读了官方 Akka Fault Tolerance documentation,但该文档中没有任何地方明确说明 when/where/how 触发了监督策略。

所以我问:什么时候使用监督策略? 当 child actor 从其 onReceive 方法中抛出 Throwable 时?或者有什么不同?

你是对的,除了它在默认决策规则中包含可抛出的对象,即错误和异常,并且它在 Actor 抛出可抛出的任何时候运行。根据http://doc.akka.io/docs/akka/2.0/java/fault-tolerance.html#default-supervisor-strategy,默认情况下,如果没有定义监管者策略或者它没有覆盖(用户创建的)Actor 抛出的异常,则将按顺序执行以下规则,直到触发一个规则:

  1. ActorInitializationException 将停止失败的子 actor
  2. ActorKilledException 将停止失败的子 actor
  3. 其他异常会重启失败的子actor
  4. 其他类型的 Throwable 将升级到父 actor

如果您还没有看过的话,http://doc.akka.io/docs/akka/2.3.11/general/supervision.html 有一个不错的监督审核。

Derek Wyatt 在 "Akka Concurrency" 第 8 章中对代码级别进行了很好的讨论。它主要处理 Scala 版本,但我相信 Actor 故障处理是在 Scala 中实现的(依赖于 Java)。

查看 2.3.11 源代码,默认的 Actor 故障处理决策器位于 akka-actor_2.11-2.3.11-sources.jar\akka\actor.FaultHandling.scala 并且是:

/**
   * When supervisorStrategy is not specified for an actor this
 * [[Decider]] is used by default in the supervisor strategy.
 * The child will be stopped when [[akka.actor.ActorInitializationException]],
 * [[akka.actor.ActorKilledException]], or [[akka.actor.DeathPactException]] is
 * thrown. It will be restarted for other `Exception` types.
 * The error is escalated if it's a `Throwable`, i.e. `Error`.
 */
final val defaultDecider: Decider = {
  case _: ActorInitializationException ⇒ Stop
  case _: ActorKilledException         ⇒ Stop
  case _: DeathPactException           ⇒ Stop
  case _: Exception                    ⇒ Restart
}

/**
 * When supervisorStrategy is not specified for an actor this
 * is used by default. OneForOneStrategy with decider defined in
 * [[#defaultDecider]].
 */
final val defaultStrategy: SupervisorStrategy = {
  OneForOneStrategy()(defaultDecider)
}

这与文档一致 - 在 defaultDecider 不包含显式

的范围内或多或少
case _ => Escalate // _ is the scala wildcard for anything

这是在 makeDecider 函数中实现的,如果 DefaultDecider 不匹配 Throwable,则默认为 Escalate;并且文档没有提到包含 DeathPactException 的规定可能是为了减少与细节的混淆。