如何在Akka中监督集群单身人士?

时间:2016-04-18 18:43:23

标签: akka akka-supervision akka-monitoring

我试图监督Akka演员,更具体地说是使用ClusterSingletonManager创建的Cluster Singleton。我试图更好地控制异常,日志和演员的生命周期。

不幸的是,在实现解决方案后,我使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吗?如果可能的话,我应该如何解决这个问题呢?

1 个答案:

答案 0 :(得分:3)

一种可能的解决方案是创建主管演员,该演员演员给定给定supervisorStrategy的孩子,并将消息转发给其子女。

这是主管演员:

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

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

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

以下是如何创建有监督的演员作为集群单身人士

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