如何在异常时停止Actor重新加载

use*_*074 1 scala akka

在Actor接收中抛出异常的情况下,我想阻止重新加载此actor.我知道正确的方法是覆盖supervisorStrategy,但这不起作用,如下例所示:

class MyActor extends Actor {

    println("Created new actor")

    def receive = {
        case msg =>
            println("Received message: " + msg)
            throw new Exception()
    }

    override val supervisorStrategy = OneForOneStrategy() {
        case _: Exception => Stop
    }
}

val system = ActorSystem("Test")
val actor = system.actorOf(Props(new MyActor()))
actor ! "Hello"
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,"创建的新actor"输出两次,表明在异常后再次重新加载Actor.

防止重新加载Actor的正确方法是什么?

Jef*_*ung 5

当演员覆盖默认的主管策略时,该策略适用于该演员的孩子.您的actor正在使用默认的supervisor策略,该策略在抛出异常时重新启动actor.为您的actor定义父级并覆盖该父级中的主管策略.

class MyParent extends Actor {
  override val supervisorStrategy = OneForOneStrategy() {
    case _: Exception => Stop
  }

  val child = context.actorOf(Props[MyActor])

  def receive = {
    case msg =>
      println(s"Parent received the following message and is sending it to the child: $msg")
      child ! msg
  }
}

class MyActor extends Actor {
  println("Created new actor")

  def receive = {
    case msg =>
      println(s"Received message: $msg")
      throw new Exception()
  }
}

val system = ActorSystem("Test")
val actor = system.actorOf(Props[MyParent])
actor ! "Hello"
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,a MyActor被创建为子的MyParent.当后者收到"Hello"消息时,它会向孩子发送相同的消息.子节点在抛出异常时被停止,"Created new actor"因此只打印一次.