java - Akka - 在 child 发生异常后 parent 如何向 child 发送消息

标签 java akka akka-supervision

假设我有一个 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/

相关文章:

java - 没有绑定(bind) akka.actor.ActorRef 的实现

java - 在 AKKA 中,调用 supervisor 的 shutdown 会停止它所监督的所有 actor 吗?

akka.net - 无法让主管策略在 Akka.NET 中工作

java - 在 hashmap 中读取 excel 文件时出现 for 循环错误

java - ArrayList降序使用比较方法

java - 如何将位列设置为空?

java - Akka - 如何重新启动路由器生成的子进程?

java - 如何比较两个 long 的高 40 位

AKKA 关机模式不起作用

akka - 在 Akka 中等待多个结果