Akka.net - 协调器的额外错误处理

Akka.net - additional error handling by coordinator

给定一个 Akka。net-based actor 系统具有一些基本结构,例如:

/user
  /coordinator
    /child (x1000, with RoundRobinPool router)

Coordinator actor 使用 Directive.Restart 定义监督策略。

Child actors 可能由于多种原因而失败(例如,ArithmeticExceptionInvalidOperationExceptionMyCustomException)。

但是当 child 因 MyCustomException 失败时,我希望能够在不更改默认监督机制的情况下以某种方式额外处理它(重启方法在这里应该仍然有效)。 例如,添加带有异常详细信息的 Console.Writeline

如何实施?

一般来说,MyCustomException 表示异常发生时您是负责人,您可以立即将其记录在子逻辑中,而无需将其提升到父逻辑。但是,如果不可能,您可以像这样定义自己的主管策略 class:

public class MySupervisorStrategy : OneForOneStrategy
{
    public MySupervisorStrategy(ILoggingAdapter log) : base(reason =>
        {
            if (reason is MyCustomException)
            {
                log.Error(reason.Message);
                return Directive.Restart;
            }

            return Akka.Actor.SupervisorStrategy.DefaultDecider.Decide(reason);
        })
    {
    }
}

有两种方法可以将它应用到您的演员身上:

  1. 使用 Props.Create<MyActor>().WithSupervisorStrategy(new MySupervisorStrategy(system.Log) 直接从您的演员系统应用它。
  2. 通过重写 actor 的 SupervisorStrategy 方法将其直接附加到 actor 的逻辑中(使用 Context.GetLogger() 接收当前 actor 的日志实例)。

第二个选项不太灵活,但在需要使用远程部署方案的情况下可能会更好。