gpt4 book ai didi

scala - 如何发现 Scala 远程 Actor 死亡?

转载 作者:行者123 更新时间:2023-12-04 07:44:55 28 4
gpt4 key购买 nike

在 Scala 中,当另一个(远程)actor 终止时,可以通过设置 trapExit 标志并使用第二个 actor 作为参数调用 link() 方法来通知一个 actor。在这种情况下,当远程参与者通过调用 exit() 结束其工作时,第一个参与者会通过接收 Exit 消息得到通知。

但是当远程参与者以一种不太优雅的方式终止时会发生什么(例如,它运行的虚拟机崩溃)?换句话说,本地参与者如何发现远程参与者不再可用?当然,我更喜欢(如果可能)本地参与者可以通过类似于 Exit 的消息来通知,但这似乎不可行。我错过了什么吗?我应该不断轮询远程参与者的状态(在这种情况下我不知道哪种方法是最好的)还是有更聪明的解决方案?

最佳答案

Actors in Scala 提及(未亲自测试):

捕获终止通知。

In some cases, it is useful to receive termination notifications as messages in the mailbox of a monitoring actor.
For example, a monitoring actor may want to rethrow an exception that is not handled by some linked actor.
Or, a monitoring actor may want to react to normal termination, which is not possible by default.

Actors can be configured to receive all termination notifications as normal messages in their mailbox using the Boolean trapExit flag. In the following example actor b links itself to actor a:


val a = actor { ... }
val b = actor {
self.trapExit = true
link(a)
...
}

Note that before actor b invokes link it sets its trapExit member to true;
this means that whenever a linked actor terminates (normally or abnormally) it receives a message of type Exit.
Therefore, actor b is going to be notified whenever actor a terminates (assuming that actor a did not terminate before b’s invocation of link).



那么“当远程参与者以不太优雅的方式终止时会发生什么”?
它应该收到 Exit即使在异常终止的情况下也可以发送消息。
val b = actor {
self.trapExit = true
link(a)
a ! 'start
react {
case Exit(from, reason) if from == a =>
println("Actor 'a' terminated because of " + reason)
}
}

关于scala - 如何发现 Scala 远程 Actor 死亡?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4304506/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com