我正在使用Akka,我想为User Guardian actor定义自己的监督策略。我定义了两种类型的actor,称为TaskActor和MessageActor。他们被实例化为顶级演员。 我希望用户监护人应用以下监督策略:当他们抛出异常时停止TaskActor和Resume MessageActor(我不介意抛出什么特定类型的异常)。我该怎么办?
答案 0 :(得分:0)
我找到了以下解决方案:
object ActorClassUtil {
val ACTORS_PACKAGE = "utils.actors."
val TASK_ACTOR_CLASS_NAME = ACTORS_PACKAGE + "TaskActor"
val MSG_ACTOR_CLASS_NAME = ACTORS_PACKAGE + "MessageActor"
def getFailedActorClassFrom(e: Exception): String = {
val stackTrace = e.getStackTrace
// FQCN (Fully Qualified Class Name)
stackTrace(0) getClassName
}
}
class UserGuardianSupervisorStrategy extends SupervisorStrategyConfigurator {
import ActorClassUtil._
def create(): OneForOneStrategy = {
OneForOneStrategy(maxNrOfRetries = 20, withinTimeRange = 1 minute) {
case _: ActorInitializationException => Stop
case _: ActorKilledException => Stop
case _: DeathPactException => Stop
case exception: Exception =>
val actorClassName = getFailedActorClassFrom(exception)
if (actorClassName startsWith TASK_ACTOR_CLASS_NAME)
Stop
else
if (actorClassName startsWith MSG_ACTOR_CLASS_NAME)
Resume
else
Stop
}
}
}