在上一篇討論中我們談到了監(jiān)管:在Akka中就是一種直屬父子監(jiān)管樹(shù)結(jié)構(gòu),父級(jí)Actor負(fù)責(zé)處理直屬子級(jí)Actor產(chǎn)生的異常。當(dāng)時(shí)我們把BackoffSupervisor作為父子監(jiān)管方式的其中一種。實(shí)際上BackoffSupervisor與定義了supervisorStrategy的Actor有所不同。我們應(yīng)該把BackoffSupervisor看作是一個(gè)一體化的Actor。當(dāng)然,它的實(shí)現(xiàn)方式還是由一對(duì)父子Actor組成。監(jiān)管策略(SupervisorStrategy)是在BackoffSupervisor的內(nèi)部實(shí)現(xiàn)的。從外表上BackoffSupervisor就像是一個(gè)Actor,運(yùn)算邏輯是在子級(jí)Actor中定義的,所謂的父級(jí)Actor除監(jiān)管之外沒(méi)有任何其它功能,我們甚至沒(méi)有地方定義父級(jí)Actor的功能,它的唯一功能是轉(zhuǎn)發(fā)收到的信息給子級(jí),是嵌入BackoffSupervisor里的。所以我們雖然發(fā)送消息給BackoffSupervisor,但實(shí)際上是在與它的子級(jí)交流。我們看看下面這個(gè)例子:
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) => //模擬子級(jí)功能 log.info(s"Child received message: ${msg}") } }object Supervisor { def props: Props = { //在這里定義了監(jiān)管策略和child Actor構(gòu)建 def decider: PartialFunction[Throwable, SupervisorStrategy.Directive] = { case _: InnerChild.ChildException => SupervisorStrategy.Restart } val options = Backoff.onFailure(InnerChild.props, &quo