在Actor接收中抛出异常的情况下,我想阻止重载此actor。我知道这样做的正确方法是重写supervisorStrategy,但这不起作用,如下例所示:
date
当我运行此代码"创建新演员"输出两次,表明在异常后再次重新加载Actor。
防止重新加载Actor的正确方法是什么?
答案 0 :(得分: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"
在上面的示例中,MyActor
被创建为MyParent
的子项。当后者收到"Hello"
消息时,它会向子节点发送相同的消息。该子项在抛出异常时被停止,因此"Created new actor"
仅打印一次。