在上一篇討論中我們談到了監(jiān)管:在Akka中就是一種直屬父子監(jiān)管樹結構,父級Actor負責處理直屬子級Actor產(chǎn)生的異常。當時我們把BackoffSupervisor作為父子監(jiān)管方式的其中一種。實際上BackoffSupervisor與定義了supervisorStrategy的Actor有所不同。我們應該把BackoffSupervisor看作是一個一體化的Actor。當然,它的實現(xiàn)方式還是由一對父子Actor組成。監(jiān)管策略(SupervisorStrategy)是在BackoffSupervisor的內部實現(xiàn)的。從外表上BackoffSupervisor就像是一個Actor,運算邏輯是在子級Actor中定義的,所謂的父級Actor除監(jiān)管之外沒有任何其它功能,我們甚至沒有地方定義父級Actor的功能,它的唯一功能是轉發(fā)收到的信息給子級,是嵌入BackoffSupervisor里的。所以我們雖然發(fā)送消息給BackoffSupervisor,但實際上是在與它的子級交流。我們看看下面這個例子:
package backoffSupervisorDemo import akka.actor._ import akka.pattern._ import backoffSupervisorDemo.InnerChild.TestMessage import scala.concurrent.duration._object InnerChild { case class TestMessage(msg: String) class ChildException extends Exception def props = Props[InnerChild] }class InnerChild extends Actor with ActorLogging { import InnerChild._ override def receive: Receive = { case TestMessage(msg) => //模擬子級功能 log.info(s"Child received message: ${msg}") } }object Supervisor { def props: Props = { //在這里定義了監(jiān)管策略和child Actor構建 def decider: PartialFunction[Throwable, SupervisorStrategy.Directive] = { case _: InnerChild.ChildException => SupervisorStrategy.Restart } val options = Backoff.onFailure(InnerChild.props, &quo