我将探索 Akka
生命周期和 Akka
参与者监督策略。我正在创建自己的异常并重写 public SupervisorStrategy SupervisorStrategy() 方法来探索 akka 的生命周期及其恢复策略。以下是我的代码:
public class JavaActor extends AbstractActor {
@Override
public PartialFunction<Object, BoxedUnit> receive() {
System.out.println("---- In the receive method "+Thread.currentThread().getName());
return ReceiveBuilder.
matchEquals("Ping" , s -> {
System.out.println("$$$ Ping Match Successfully");
throw new EsclateException("Might be esclate");
}).
matchAny(x -> {
System.out.println("### Matched value is : "+ x);
sender().tell(new Status.Failure(new Exception("unknown message")), self());
}).build();
}
@Override
public void preRestart(Throwable reason, Option<Object> message) throws Exception {
super.preRestart(reason, message);
System.out.println(">>> Actor preRestart method calls : "+Thread.currentThread().getName());
}
@Override
public void postRestart(Throwable reason) throws Exception {
super.postRestart(reason);
System.out.println(">>> Actor postRestart method calls : "+Thread.currentThread().getName());
}
@Override
public void preStart() throws Exception {
super.preStart();
System.out.println(">>> Actor preStart method calls "+Thread.currentThread().getName());
}
@Override
public void postStop() throws Exception {
super.postStop();
System.out.println(">>> Actor postStop method calls "+Thread.currentThread().getName());
}
@Override
public SupervisorStrategy supervisorStrategy() {
System.out.println("**** SupervisorStrategy Override Successfully ****");
return new OneForOneStrategy(5, Duration.create(1, TimeUnit.MINUTES),
DeciderBuilder.match(ResumeException.class, e -> SupervisorStrategy.resume())
.match(RestartException.class, e -> SupervisorStrategy.restart())
.match(StopException.class, e -> SupervisorStrategy.stop())
.match(EsclateException.class, e -> SupervisorStrategy.escalate())
.matchAny(e -> SupervisorStrategy.escalate()).build());
}}
在 receive()
方法中,当我抛出 EsclateException
时,日志会继续,不会终止 actor。但是,当我用 throw new Error()
替换异常代码时,参与者会停止工作并终止。从输出来看,我的 SupervisorStrategy
未注册,并且 Actor 在默认的 SupervisorStrategy
上运行。我如何注册我的策略?
下面是我的调用代码:
public class JavaActorTest {
public static ActorSystem system;
@BeforeClass
public static void start() {
system = ActorSystem.create("ActorLifeCycleTest");
}
@AfterClass
public static void cleanup() {
JavaTestKit.shutdownActorSystem(system);
system = null;
}
@Test
public void testActorCreation(){
TestActorRef<JavaActor> actorRef = TestActorRef.create(system, Props.create(JavaActor.class));
actorRef.tell("Ping", ActorRef.noSender());
assertThat(true, is(true));
}}
最佳答案
一个 Actor 是由其父 Actor 而非其自身进行监督,因此当 Actor 失败时,将应用其父 Actor 的 supervisorStrategy
。
在您的示例中,您不包括您自己的 parent ,因此应用了用户监护人 Actor 监督。
您可以在此处的文档中阅读有关监督的更多信息:http://doc.akka.io/docs/akka/2.4/general/supervision.html#supervision
关于java - Akka:自定义 akka 监督策略未使用 Java 注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39018656/