如何监督 Akka 中的集群单例?

How to supervise cluster singleton in Akka?

我正在尝试监督 Akka Actor,更具体地说是使用 ClusterSingletonManager 创建的 Cluster Singleton。我正在努力实现对异常、日志和 Actor 生命周期的更多控制。

不幸的是,在实施解决方案后,我让一个 Singleton Actor 抛出异常,但日志中没有显示任何内容,Actor 或 Cluster 也没有关闭。

我的实现如下:

object SingletonSupervisor {
  case class CreateSingleton(p: Props, name: String)
}

class SingletonSupervisor extends Actor with ActorLogging {
  override val supervisorStrategy =
    OneForOneStrategy(maxNrOfRetries = 0, withinTimeRange = 1.minute) {
      case x: ActorInitializationException =>
        log.error(s"Actor=<${x.getActor}> trowed an exception=<${x.getCause}> with message=<${x.getMessage}>")
        Stop

      case x: ActorKilledException => Stop

      case x: DeathPactException => Stop

      case x: Exception =>
        log.error(s"Some actor threw an exception=<${x.getCause}> with message=<${x.getMessage}>, trace=<${x.getStackTrace}>")
        Escalate
    }

  def receive = {
    case CreateSingleton(p: Props, name: String) =>
      sender() ! context.actorOf(p)
      context.actorOf(ClusterSingletonManager.props(
        singletonProps = p,
        terminationMessage = PoisonPill,
        settings = ClusterSingletonManagerSettings(context.system)),
        name = name)
  }
}

那么,是否有可能管理一个 Cluster Singlegon?如果可能,我该如何解决这个问题?

一个可能的解决方案是创建主管角色,它在给定 child 和给定 supervisorStrategy 的情况下产生,并将消息转发到它的 child。

这里是监督演员:

class SupervisorActor(childProps: Props, override val supervisorStrategy) extends Actor {

  val child = context.actorOf(childProps, "supervised-child")

  def receive: Receive = {
    case msg => child forward msg
  }
}

下面是如何将受监督的 actor 创建为集群单例

context.actorOf(ClusterSingletonManager.props(
        singletonProps = Props(classOf[SupervisorActor], p, supervisorStrategy),
        terminationMessage = PoisonPill,
        settings = ClusterSingletonManagerSettings(context.system)),
        name = name)