如果我在Scala中为演员定义主管策略,我该如何同时使用OneForOneStrategy
和AllForOneStrategy
?是否有一种简单的方法来组合它们,还是我必须定义自定义SupervisorStrategy
?
这是一个例子:
class MyActor extends Actor {
override val supervisorStrategy = OneForOneStrategy() {
case _: NullPointerException => Restart
case _: FileNotFoundException => Restart // here I want to restart all children
case _: Exception => Escalate
}
}
如果我必须编写自己的主管策略,我该怎么做?我找不到任何例子。
答案 0 :(得分:0)
您必须定义自定义主管策略。对于您的特定用例,以下自定义策略将起作用:
package akka.actor
import java.io.FileNotFoundException
import scala.concurrent.duration._
case class CustomStrategy(
maxNrOfRetries: Int = -1,
withinTimeRange: Duration = Duration.Inf,
override val loggingEnabled: Boolean = true)(val decider: SupervisorStrategy.Decider)
extends SupervisorStrategy {
import SupervisorStrategy._
private val retriesWindow = (maxNrOfRetriesOption(maxNrOfRetries), withinTimeRangeOption(withinTimeRange).map(_.toMillis.toInt))
def handleChildTerminated(context: ActorContext, child: ActorRef, children: Iterable[ActorRef]): Unit = ()
def processFailure(context: ActorContext, restart: Boolean, child: ActorRef, cause: Throwable, stats: ChildRestartStats, children: Iterable[ChildRestartStats]): Unit = {
if (cause.isInstanceOf[FileNotFoundException]) {
// behave like AllForOneStrategy
if (children.nonEmpty) {
if (restart && children.forall(_.requestRestartPermission(retriesWindow)))
children foreach (crs ⇒ restartChild(crs.child, cause, suspendFirst = (crs.child != child)))
else
for (c ← children) context.stop(c.child)
}
} else {
// behave like OneForOneStrategy
if (restart && stats.requestRestartPermission(retriesWindow))
restartChild(child, cause, suspendFirst = false)
else
context.stop(child)
}
}
}
Here是测试上述策略的要点。规范创建了一个使用CustomStrategy
的主管,它创建了两个孩子。当一个孩子抛出NullPointerException
时,只有那个孩子重新开始;当孩子抛出FileNotFoundException
时,两个孩子都会重新开始。
关于自定义策略的一些注意事项:
SupervisorStrategy
,并根据现有策略here建模。 akka.actor
包中定义,可以访问那里的包私有成员。processFailure
,必须在扩展SupervisorStrategy
的类中重写的方法之一,在Restart
和Stop
上调用,因此对于您的方案,我们定义那里的习惯行为。