假设我有一个父
actor,它一次发送一条消息给它的子
actor。
当子进程处理完当前消息后,它会通知父进程,然后父进程将向子进程发送一条新消息。
为了即使子进程因某个消息而崩溃也能保持此循环,我向父进程添加了 SupervisorStrategy:
private static SupervisorStrategy strategy =
new OneForOneStrategy(10, Duration.create("1 minute"),
new Function<Throwable, SupervisorStrategy.Directive>() {
@Override
public SupervisorStrategy.Directive apply(Throwable t) {
if (t instanceof NullPointerException) {
return resume();
} else {
return escalate();
}
}
});
这个想法是,无论 child 发生什么,它都会恢复,并且 parent 将能够向其发送下一条消息。
但是父级如何知道错误何时发生,以便发送下一条消息?
什么因素会触发 parent 发现 child 发生了什么事?
是否有类似“onChileError”方法的东西需要重写?
(将欣赏 Java over Scala 示例)
谢谢。
最佳答案
When the child is done processing the current message it notifies the parent that in it turn will send a new message to the child....
The idea is that no matter what heppens to the child, it will resume and the parent will be able to send it the next message.
您当前的主管策略执行以下操作:如果在子级中引发 NullPointerException
,则子级将恢复,就像什么也没发生一样。如果抛出不同的异常,它会进一步升级到 Actor 层次结构,这可能意味着 default supervisor strategy启动,在这种情况下子进程将重新启动。如果您希望子进程无论异常情况如何都能恢复,请将您的策略更改为以下内容(我使用的是 DeciderBuilder
):
private static SupervisorStrategy strategy =
new OneForOneStrategy(10, Duration.create(1, TimeUnit.MINUTES), DeciderBuilder.
match(Exception.class, e -> {
// getSelf() is the parent and getSender() is the child
GiveMeAnotherMessage message = // ...
getSelf().tell(message, getSender());
resume();
})
.matchAny(o -> escalate())
.build());
@Override
public SupervisorStrategy supervisorStrategy() {
return strategy;
}
But how the parent knows when the error occured, in order to send the next message?
What is the trigger for the parent that something happend to the child?
Is there something like "onChileError" method that I need to override?
决策者可以通过getSender()
访问当前失败的子进程的引用,因此您所要做的就是向父进程发送一条消息,让其知道子进程已准备好处理另一条消息来自策略本身,如上面的代码所示。
关于java - Akka - 在 child 发生异常后 parent 如何向 child 发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45731801/