Akka主管战略 - 正确的用例

时间:2016-09-16 01:04:51

标签: scala design-patterns akka supervisorstrategy

我一直在使用Akka Supervisor Strategy来处理业务逻辑异常。

阅读最着名的Scala博客系列之一Neophyte,我发现他为我一直在做的事情提供了不同的目的。

示例:

假设我有一个应该联系外部资源的HttpActor,如果它已经关闭,我会抛出异常,现在是ResourceUnavailableException

如果我的主管捕获了这个,我会在我的HttpActor上调用一个Restart,在我的HttpActor preRestart方法中,我会调用schedulerOnce来重试。

演员:

class HttpActor extends Actor with ActorLogging {

  implicit val system = context.system

  override def preRestart(reason: Throwable, message: Option[Any]): Unit = {
    log.info(s"Restarting Actor due: ${reason.getCause}")
    message foreach { msg =>
      context.system.scheduler.scheduleOnce(10.seconds, self, msg)
    }
  }

  def receive = LoggingReceive {

    case g: GetRequest =>
      doRequest(http.doGet(g), g.httpManager.url, sender())
  }

主管:

class HttpSupervisor extends Actor with ActorLogging with RouterHelper {

  override val supervisorStrategy =
    OneForOneStrategy(maxNrOfRetries = 5) {
      case _: ResourceUnavailableException   => Restart
      case _: Exception                      => Escalate
    }

  var router = makeRouter[HttpActor](5)

  def receive = LoggingReceive {
    case g: GetRequest =>
      router.route(g, sender())

    case Terminated(a) =>
      router = router.removeRoutee(a)
      val r = context.actorOf(Props[HttpActor])
      context watch r
      router = router.addRoutee(r)
  }
}

这里有什么意义?

如果我的doRequest方法抛出ResourceUnavailableException,主管将获得该操作并重新启动actor,强制它在一段时间后重新发送消息,根据调度程序。我看到的优点是我可以免费获得重试次数以及处理异常本身的好方法。

现在看一下博客,他展示了一种不同的方法,以防你需要重试,只需发送这样的信息:

def receive = {
  case EspressoRequest =>
    val receipt = register ? Transaction(Espresso)
    receipt.map((EspressoCup(Filled), _)).recover {
      case _: AskTimeoutException => ComebackLater
    } pipeTo(sender)

  case ClosingTime => context.system.shutdown()
}

AskTimeoutException的{​​{1}}的情况下,他将结果作为Future对象进行管道处理,他将执行此操作:

ComebackLater

对我而言,这几乎就是你可以用策略管理器做的事情,但是以手动的方式,没有内置的重试逻辑数。

那么这里最好的方法是什么?为什么?我使用akka主管策略的概念是完全错误的吗?

1 个答案:

答案 0 :(得分:4)

您可以使用BackoffSupervisor

  

作为内置模式提供akka.pattern.BackoffSupervisor实现所谓的指数退避监督策略,在失败时再次启动子actor,每次重启之间的时间延迟都会增加。

val supervisor = BackoffSupervisor.props(
  Backoff.onFailure(
    childProps,
    childName = "myEcho",
    minBackoff = 3.seconds,
    maxBackoff = 30.seconds,
    randomFactor = 0.2 // adds 20% "noise" to vary the intervals slightly 
  ).withAutoReset(10.seconds) // the child must send BackoffSupervisor.Reset to its parent 
  .withSupervisorStrategy(
    OneForOneStrategy() {
      case _: MyException => SupervisorStrategy.Restart
      case _ => SupervisorStrategy.Escalate
    }))