我有以下顶级(“父母最多”)演员:
// Groovy pseudo-code
class Master extends UntypedActor {
ActorRef child1
ActorRef child2
ActorRef child3
ActorRef backup
@Override
void onReceive(Object message) throws Exception {
if(message instanceof Terminated) {
Terminated terminated = message as Terminated
if(terminated.actor != backup) {
terminated.actor = backup
} else {
// TODO: What to do here? How to escalate from here?
}
} else {
child1.tell(new DoSomething(message), getSelf())
child2.tell(new DoSomethingElse(message), getSelf())
child3.tell(new DoSomethingElser(message, getSelf())
}
}
@Override
SupervisorStrategy supervisorStrategy() {
new OneForOneStrategy(10, Duration.minutes(“1 minute”, new Future<Throwable, SupervisorStrategy.Directive> {
@Override
Directive apply(Throwable t) throws Exception {
if(isRecoverable(t) { // Don’t worry about how/where this is defined or how it works
SupervisorStrategy.stop()
} else {
SupervisorStrategy.escalate()
}
}
})
}
}
正如您所看到的,它监督着三个孩子,当这3个孩子抛出“可恢复”的异常时,它们会被停止并被替换为备份。到目前为止,非常好。
我现在面临的问题是,如果备份演员抛出任何 throwable,我想考虑这个Master
演员(实际上,我的应用程序一般)是处于无法继续处理任何输入的状态,并将异常升级为监护人级别。
我是Akka的新手,不知道在哪里放这个代码,它应该是什么样子。同样,我只需要逻辑说:
Master
的父级,这应该是Akka“guaradian”actor / construct 第一部分是我们需要知道何时从备份中抛出异常;我可以处理这一部分,所以让我们假设我们的策略现在看起来像这样:
@Override
SupervisorStrategy supervisorStrategy() {
new OneForOneStrategy(10, Duration.minutes(“1 minute”, new Future<Throwable, SupervisorStrategy.Directive> {
@Override
Directive apply(Throwable t) throws Exception {
if(wasThrownFromBackup(t)) {
SupervisorStrategy.escalate()
} else if(isRecoverable(t) {
SupervisorStrategy.stop()
} else {
SupervisorStrategy.escalate()
}
}
})
}
但正如你所看到的,我仍然在努力实现“退出演员系统”的升级。想法? Java代码示例非常首选,因为Scala对我来说就像是象形文字。
答案 0 :(得分:1)
看一下“收割者”&#39;这里的模式http://letitcrash.com/post/30165507578/shutdown-patterns-in-akka-2很抱歉它在Scala中,但我认为很容易翻译成Java。
另请查看https://groups.google.com/forum/#!topic/akka-user/QG_DL7FszMU
您应该在配置中进行设置
akka.actor.guardian-supervisor-strategy = "akka.actor.StoppingSupervisorStrategy"
这将导致任何顶级&#39;升级为系统停止的演员。然后你实现另一个名为“Reaper&#39;”的顶级演员。 (或任何你想称之为的)只有一份工作,观看主要顶级演员并在顶级演员停止时采取行动(例如context.system.shutdown()
)。
我不知道akka java API,因此无法为您提供一个确切的示例,但在Scala中,来自上面的LetItCrash博客,它看起来像:
import akka.actor.{Actor, ActorRef, Terminated}
import scala.collection.mutable.ArrayBuffer
object Reaper {
// Used by others to register an Actor for watching
case class WatchMe(ref: ActorRef)
}
abstract class Reaper extends Actor {
import Reaper._
// Keep track of what we're watching
val watched = ArrayBuffer.empty[ActorRef]
// Derivations need to implement this method. It's the
// hook that's called when everything's dead
def allSoulsReaped(): Unit
// Watch and check for termination
final def receive = {
case WatchMe(ref) =>
context.watch(ref)
watched += ref
case Terminated(ref) =>
watched -= ref
if (watched.isEmpty) allSoulsReaped()
}
}
class ProductionReaper extends Reaper {
// Shutdown
def allSoulsReaped(): Unit = context.system.shutdown()
}
在您的应用程序启动中,您创建主操作员,创建收割者,向收割者发送WatchMe(masterActor)
消息。