本文整理汇总了Scala中akka.actor.SupervisorStrategy.Restart类的典型用法代码示例。如果您正苦于以下问题:Scala Restart类的具体用法?Scala Restart怎么用?Scala Restart使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Restart类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: CustomOneForOneUser
//设置package包名称以及导入依赖的类
package com.example.supervisor
import akka.actor.SupervisorStrategy.{Restart, Stop}
import akka.actor.{Actor, ActorLogging, ActorRef, OneForOneStrategy}
class CustomOneForOneUser extends Actor with ActorLogging {
// Map that keeps track of how often a given child has been restarted
var restarts = Map.empty[ActorRef, Int].withDefaultValue(0)
// Using the default parameters for a SupervisorStrategy mean "arbitarily
// often over forever"
override val supervisorStrategy = OneForOneStrategy() {
case _: ArithmeticException =>
restarts(sender) match {
case tooManyRestarts if tooManyRestarts > 15 =>
restarts -= sender
Stop
case n =>
restarts = restarts.updated(sender, n+1)
Restart
}
}
override def receive: Receive = ???
}
示例2: ProcrusteanManager
//设置package包名称以及导入依赖的类
package com.example.supervisor
import akka.actor.SupervisorStrategy.{Escalate, Restart, Stop}
import akka.actor.{Actor, ActorLogging, AllForOneStrategy}
import scala.concurrent.duration._
class ProcrusteanManager extends Actor with ActorLogging {
override val supervisorStrategy =
AllForOneStrategy(maxNrOfRetries = 5,
withinTimeRange = 5 seconds,
loggingEnabled = true) {
case _: IllegalStateException => Restart
case _: IllegalArgumentException => Stop
case _: NullPointerException => Stop
case _: Exception => Escalate
}
override def receive: Receive = ???
}
示例3: TelemetryDumperSupervisor
//设置package包名称以及导入依赖的类
package sample.kamon
import akka.actor.SupervisorStrategy.Restart
import akka.actor.{Actor, ActorLogging, OneForOneStrategy, Props}
import sample.kamon.TelemetryDumperSupervisor.Saved
import scala.util.Random
class TelemetryDumperSupervisor extends Actor with ActorLogging {
log.info("TelemetryDumperSupervisor started!")
override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) {
case e: Exception =>
log.error(e, "There was an error when trying to save telemetry data, restarting.")
Restart
}
def receive: Receive = {
case telemetry: Int =>
Thread.sleep(40 * Random.nextInt(10))
context.actorOf(TelemetryDumper.props(new SimpleBackoffStrategy, telemetry))
case Saved(telemetry) =>
//Make some post process
}
}
object TelemetryDumperSupervisor {
def props(): Props = Props(classOf[TelemetryDumperSupervisor])
case class Saved(telemetry: Int)
}
示例4: ArithmeticService
//设置package包名称以及导入依赖的类
package com.bob.akka.supervision
import akka.actor.SupervisorStrategy.{Restart, Stop}
import akka.actor._
import com.bob.akka.supervision.FlakyExpressionCalculator.{FlakinessException, Result}
class ArithmeticService extends Actor with ActorLogging {
override def receive: Receive = {
case e: Expression =>
val worker = context.actorOf(FlakyExpressionCalculator.props(expr = e, position = FlakyExpressionCalculator.Left))
pendingWorkers += worker -> sender()
case Result(originalExpression, value, _) =>
notifyConsumerSuccess(worker = sender(), result = value)
}
var pendingWorkers = Map[ActorRef, ActorRef]()
def notifyConsumerFailure(worker: ActorRef, failure: Throwable): Unit = {
pendingWorkers.get(worker).foreach { x => x ! Status.Failure(failure) }
pendingWorkers -= worker
}
def notifyConsumerSuccess(worker: ActorRef, result: Int): Unit = {
pendingWorkers.get(worker) foreach {
_ ! result
}
pendingWorkers -= worker
}
override val supervisorStrategy = OneForOneStrategy(loggingEnabled = false) {
case _: FlakinessException =>
log.warning("Evaluation of a top level expression failed, restarting.")
Restart
case e: ArithmeticException =>
log.error("Evaluation failed because of: {}", e.getMessage)
notifyConsumerFailure(worker = sender(), failure = e)
Stop
case e =>
log.error("Unexpected failure: {}", e.getMessage)
notifyConsumerFailure(worker = sender(), failure = e)
Stop
}
}
示例5:
//设置package包名称以及导入依赖的类
package actors.workflow
import actors.WorkflowLog.LogMessage
import akka.actor.SupervisorStrategy.{Restart, Stop}
import akka.actor.{Actor, ActorLogging, OneForOneStrategy}
import com.amazonaws.{AmazonClientException, AmazonServiceException}
import scala.concurrent.duration._
trait AWSSupervisorStrategy extends Actor with ActorLogging {
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 20, loggingEnabled = true) {
case ex: AmazonServiceException =>
ex.getErrorCode match {
case "ServiceUnavailable" | "Throttling" =>
log.debug("Supervisor Authorized Restart")
Restart
case _ =>
context.parent ! LogMessage(ex.toString)
Stop
}
case _: AmazonClientException =>
log.debug("Supervisor Authorized Restart")
Restart
case ex: Exception =>
context.parent ! LogMessage(ex.toString)
Stop
}
}
示例6: ColetorNotificacoesActor
//设置package包名称以及导入依赖的类
package com.exemplo5
import akka.actor.SupervisorStrategy.{Escalate, Restart, Resume, Stop}
import akka.actor.{Actor, OneForOneStrategy, Props, Terminated}
import akka.routing.RoundRobinPool
import com.common.Notificacao
import com.common.TipoNotificacao._
import com.exemplo5.ColetorNotificacoesActor.{ContarNotificacoes, EnviarNotificacao}
import com.exemplo5.NotificacaoPagamentoActor.NotificarPagamento
import scala.collection.mutable.ListBuffer
import scala.concurrent.duration._
class ColetorNotificacoesActor extends Actor {
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException => Resume
case _: NullPointerException => Restart
case _: IllegalArgumentException => Restart
case _: Exception => Escalate
}
var notificacoes = new ListBuffer[Notificacao]()
val notificacaoPagamentoActor = context.actorOf(RoundRobinPool(10).props(Props[NotificacaoPagamentoActor]), "NotificacaoPagamentoActor")
context.watch(notificacaoPagamentoActor)
def receive = {
case EnviarNotificacao(notificacao) => {
notificacoes += notificacao
notificacao.tipo match {
case PAGAMENTO => notificacaoPagamentoActor ! NotificarPagamento(notificacao)
case SAQUE => notificacaoPagamentoActor ! NotificarPagamento(notificacao)
case TRANSFERENCIA => notificacaoPagamentoActor ! NotificarPagamento(notificacao)
}
}
case ContarNotificacoes => sender ! notificacoes.size
case Terminated(ator) => println(s"############### Ator ${ator.path} finalizado ##############")
}
}
object ColetorNotificacoesActor {
case object ContarNotificacoes
case class EnviarNotificacao(notificacao: Notificacao)
}
示例7: StreamActor
//设置package包名称以及导入依赖的类
import akka.NotUsed
import akka.actor.SupervisorStrategy.Restart
import akka.actor.{Actor, OneForOneStrategy, SupervisorStrategy}
import akka.stream.scaladsl.{Sink, Source}
import akka.stream.{ActorMaterializer, OverflowStrategy, ThrottleMode}
import scala.concurrent.duration.Duration
import scala.io.Source.fromFile
class StreamActor extends Actor {
override def receive: Receive = {
case StreamBook(filename) =>
val materializer = ActorMaterializer.create(context) // Materializing and running a stream always requires a Materializer to be in implicit scope.
val sink = Source
.actorRef(1000, OverflowStrategy.dropNew) // If the buffer is full when a new element arrives, drops the new element.
.throttle(1, Duration(1, "seconds"), 1, ThrottleMode.shaping) // throttle - to slow down the stream to 1 element per second.
.to(Sink.actorRef(sender, NotUsed)) // Sink is a set of stream processing steps that has one open input. Can be used as a Subscriber.
.run()(materializer)
val lines = fromFile(filename).getLines
lines.foreach(line => sink ! StreamLine(line))
}
override def supervisorStrategy: SupervisorStrategy =
OneForOneStrategy(10, Duration(60, "seconds")) {
case _: Exception => Restart
}
}
case class StreamBook(fileName: String)
case class StreamLine(line: String)
示例8: ExceptionDetector
//设置package包名称以及导入依赖的类
package me.invkrh.raft.kit
import akka.actor.{Actor, ActorRef, OneForOneStrategy, Props}
import akka.actor.SupervisorStrategy.Restart
class ExceptionDetector(actorName: String, probes: ActorRef*) extends Actor {
override val supervisorStrategy: OneForOneStrategy = OneForOneStrategy() {
case thr: Throwable =>
probes foreach { _ ! thr }
Restart // or make it configurable/controllable during the test
}
def receive: PartialFunction[Any, Unit] = {
case p: Props => sender ! context.actorOf(p, actorName)
}
}
示例9: DatabaseActor
//设置package包名称以及导入依赖的类
package com.example.usecase.datapump.actor
import akka.actor.SupervisorStrategy.Restart
import akka.actor.{Actor, ActorLogging, OneForOneStrategy}
import com.example.model.Author
import com.example.service.cache.CacheService
import com.example.service.cassandra.TableFiller
class DatabaseActor[C <: CacheService[String, Author]](cache: C)
extends Actor with ActorLogging {
override val supervisorStrategy = OneForOneStrategy() {
case _ => Restart
}
override def receive: Receive = {
case authorName: String => {
log debug "===========> Author: " + authorName
val author: Option[Author] = cache.getById(authorName)
if (author.isEmpty)
log error "===========> Wrong author."
else {
log debug "===========> saving author: " + authorName
TableFiller.fillWordCountByIsbn(author.get)
sender ! authorName
}
}
case _ => log error "Wrong input to DatabaseActor!"
}
}
示例10: BotSupervisor
//设置package包名称以及导入依赖的类
package actors
import akka.actor.SupervisorStrategy.{Resume, Restart, Stop, Escalate}
import akka.actor.{OneForOneStrategy, Actor, ActorLogging, Props}
import com.typesafe.config.Config
import play.api.libs.ws.WSClient
import scala.concurrent.duration._
class BotSupervisor(wsClient: WSClient,config: Config) extends Actor with ActorLogging{
override val supervisorStrategy =
OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute) {
case _: ArithmeticException => Resume
case _: NullPointerException => Restart
case _: IllegalArgumentException => Stop
case _: Exception => Escalate
}
val tinderBot =
context
.actorOf(Props(new TinderBot(wsClient,config))
,"TinderBot")
override def preStart() = {
log.info("Starting Tinder Bot Supervisor")
tinderBot ! TinderBot.Start
}
override def receive: Receive = {
case _ =>
}
}
object BotSupervisor {
def props = Props[BotSupervisor]
}
示例11: SupervisorAllActor
//设置package包名称以及导入依赖的类
package com.nossin.ndb
import akka.actor.{Actor, AllForOneStrategy, Props}
import akka.actor.SupervisorStrategy.{Escalate, Restart, Resume, Stop}
import com.nossin.ndb.messages.Calculator.{Div, Sub}
//import com.nossin.ndb.messages.Calculator.{Add, Div, Sub}
import scala.concurrent.duration._
class SupervisorAllActor extends Actor{
override val supervisorStrategy =
AllForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 seconds)
{
case _: ArithmeticException => Restart
case _: NullPointerException => Resume
case _: IllegalArgumentException => Stop
case _: Exception => Escalate
}
val printer = context.actorOf(Props[ResultPrinterActor])
val calculator = context.actorOf(Props(classOf[CalculatorActor], printer)) //The all supervisor strategy will also restart printer!
def receive = {
case "Start" => calculator ! com.nossin.ndb.messages.Calculator.Add(10, 12)
calculator ! Sub(12, 10)
calculator ! Div(5, 2)
calculator ! Div(5, 0)
}
}
示例12: SupervisorActor
//设置package包名称以及导入依赖的类
package com.nossin.ndb
import akka.actor.SupervisorStrategy.{Escalate, Restart}
import akka.actor.{Actor, OneForOneStrategy, Props}
import com.nossin.ndb.messages.Messages.StopActor
import scala.concurrent.duration._
class SupervisorActor extends Actor {
//One for One , only restart failed actor not any others/siblings. useful if actors are independed.
override val supervisorStrategy = OneForOneStrategy(maxNrOfRetries = 10, withinTimeRange = 1 minute)
{
case _: ArithmeticException => Restart
case t =>
super.supervisorStrategy.decider.applyOrElse(t, (_: Any) => Escalate)
}
def receive = {
case (props: Props, name: String) => sender ! context.actorOf(props, name)
case StopActor(actorRef) => context.stop(actorRef)
}
}
示例13: MessageRouter
//设置package包名称以及导入依赖的类
package name.mikulskibartosz.demo.akka.router
import akka.actor.SupervisorStrategy.Restart
import akka.actor.{OneForOneStrategy, Actor, Props}
import akka.routing.{ActorRefRoutee, RoundRobinRoutingLogic, Router}
import name.mikulskibartosz.demo.akka.actors.QueryExecutor
import name.mikulskibartosz.demo.akka.messages.{ExecuteQuery, ServiceUnavailable}
import name.mikulskibartosz.demo.akka.service.Service
class MessageRouter(private val service: Service) extends Actor {
var router = {
val routees = Vector.fill(5) {
val r = context.actorOf(Props(new QueryExecutor(service)))
context watch r
ActorRefRoutee(r)
}
Router(RoundRobinRoutingLogic(), routees)
}
override def supervisorStrategy = OneForOneStrategy() {
case _ => Restart
}
def receive = {
case ExecuteQuery => router.route(ExecuteQuery, sender())
case ServiceUnavailable => context.parent ! ServiceUnavailable
}
}
示例14: TopActor
//设置package包名称以及导入依赖的类
package firecrest.actors
import javax.inject.Inject
import akka.actor.SupervisorStrategy.Restart
import akka.actor.{Actor, ActorLogging, OneForOneStrategy}
import akkaguiceutils.GuiceUtils
import firecrest.FirecrestConfiguration
class TopActor @Inject() (config: FirecrestConfiguration) extends Actor
with ActorLogging
with GuiceUtils {
override val supervisorStrategy =
OneForOneStrategy() {
case error: Throwable => {
log.warning("A child error: {}", error)
Restart
}
}
import context._
private val indexer = if (!config.enableIndexer) {
log.warning("INDEXER IS DISABLED")
Some(system.actorOf(props(classOf[IndexerActor]), "indexer"))
} else {
None
}
private val listenerSupervisor = actorOf(props(classOf[ListenerSupervisorActor]),
"listener-supervisor")
private val indexScan = actorOf(props(classOf[IndexScanActor]), "index-scan")
override def receive: Receive = {
case message =>
log.info("Unexpected: {}", message)
}
}
示例15: SupervisorStrategy
//设置package包名称以及导入依赖的类
package teleporter.integration.akka
import akka.actor.SupervisorStrategy.{Decider, Restart, Stop}
import akka.actor._
import org.apache.logging.log4j.scala.Logging
trait FaultHandling {
}
object SupervisorStrategy extends Logging {
final val defaultDecider: Decider = {
case e ?
logger.info(e.getLocalizedMessage, e)
e match {
case _: ActorInitializationException ? Stop
case _: ActorKilledException ? Stop
case _: DeathPactException ? Stop
case _: Exception ? Restart
}
}
final val defaultStrategy: SupervisorStrategy = {
OneForOneStrategy()(defaultDecider)
}
}
final class DefaultSupervisorStrategy extends SupervisorStrategyConfigurator {
override def create(): SupervisorStrategy = SupervisorStrategy.defaultStrategy
}