本文整理汇总了Scala中akka.pattern.CircuitBreaker类的典型用法代码示例。如果您正苦于以下问题:Scala CircuitBreaker类的具体用法?Scala CircuitBreaker怎么用?Scala CircuitBreaker使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CircuitBreaker类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: apply
//设置package包名称以及导入依赖的类
package org.zalando.hutmann.helpers
import akka.actor.ActorSystem
import akka.pattern.CircuitBreaker
import play.api.Configuration
import scala.concurrent.duration.{ FiniteDuration, _ }
import scala.language.postfixOps
def apply(name: Option[String] = None)(implicit configuration: Configuration, actorSystem: ActorSystem): CircuitBreaker = {
val circuitBreakerName = name.getOrElse("generic")
CircuitBreaker(
actorSystem.scheduler,
maxFailures(circuitBreakerName),
callTimeout(circuitBreakerName),
resetTimeout(circuitBreakerName)
) //TODO: implement onOpen, onClose, onHalfOpen with meters for metrics endpoint?
}
}
示例2: Main
//设置package包名称以及导入依赖的类
package reactive
import scala.concurrent.ExecutionContext
import scala.concurrent.duration.DurationInt
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.util.Timeout
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.model.headers.RawHeader
import akka.http.javadsl.server.values.Headers
import akka.http.scaladsl.model.ContentType
import akka.http.scaladsl.model.MediaType
import scala.concurrent.Future
import akka.http.scaladsl.marshalling.ToResponseMarshallable
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import RollProtocol._
import akka.pattern.CircuitBreaker
import scala.util.Success
object Main extends App {
implicit val system = ActorSystem("die-api")
implicit val executor = system.dispatcher
implicit val timeout = Timeout(1000.millis)
implicit val materializer = ActorMaterializer()
val serverBinding = Http().bindAndHandle(interface = "0.0.0.0", port = 8080, handler = mainFlow)
val guard = CircuitBreaker.apply(system.scheduler, 1, 1.second, 5.second)
def mainFlow(implicit system: ActorSystem, timeout: Timeout, executor: ExecutionContext): Route = {
get {
onSuccess(Roller.roll(Die(6))) { roll =>
complete {
roll
}
}
}
path("slow") {
get {
val guarded = guard.withCircuitBreaker(Roller.rollSlow(Die(6)))
onComplete(guarded) {
case Success(roll) => complete(roll)
case _ => complete("Server Busy")
}
}
}
}
}
示例3: Ocb
//设置package包名称以及导入依赖的类
package com.pcb.db
import akka.actor.Scheduler
import akka.pattern.CircuitBreaker
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
import scala.language.postfixOps
class Ocb (
scheduler: Scheduler,
var maxFailures: Int,
callTimeout: Int,
var resetTimeout: Int)(implicit executor: ExecutionContext) {
private var cb = newCircuitBreaker
private def newCircuitBreaker: CircuitBreaker = {
new CircuitBreaker(
scheduler,
maxFailures = maxFailures,
callTimeout = callTimeout.seconds,
resetTimeout = resetTimeout.minute)
}
def reconfigure(mf: Int, rt: Int): Boolean = {
var reconfigured = false
maxFailures = mf
resetTimeout = rt
if(cb.isClosed) {
cb = newCircuitBreaker
reconfigured = true
}
reconfigured
}
def guard[T](body: => Future[T]): Future[T] = cb.withCircuitBreaker(body)
}
示例4: Main
//设置package包名称以及导入依赖的类
package com.dazito.scala.dakkabase.circuitbreaker
import java.util.concurrent.TimeUnit
import akka.actor.{ActorSystem, Props}
import akka.pattern.{CircuitBreaker, ask}
import scala.concurrent.Await
import scala.concurrent.duration.Duration
import akka.actor.ActorSystem
import akka.pattern.CircuitBreaker
import akka.pattern.ask
import akka.util.Timeout
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
object Main {
def main(args: Array[String]): Unit = {
implicit val timeout = Timeout(2, TimeUnit.SECONDS)
val system = ActorSystem("circuit-breaker-actor-system")
val pongActor = system.actorOf(Props.create(classOf[PongActor]))
val circuitBreaker = new CircuitBreaker(
system.scheduler,
maxFailures = 3,
callTimeout = 2 seconds,
resetTimeout = 1 seconds
)
circuitBreaker.onOpen(println("On open!"))
circuitBreaker.onClose(println("On close!"))
circuitBreaker.onHalfOpen(println("On half open!"))
Await.result(pongActor ? "Ping!", Duration.create(2, TimeUnit.SECONDS))
(1 to 100000).foreach(x => {
Thread.sleep(50)
val askFuture = circuitBreaker.withCircuitBreaker(pongActor ? "Ping")
askFuture.map(x => "Got it: " + x).recover({
case t => "error: " + t.toString
}).foreach(x => println(x))
})
}
}
示例5: Retweet
//设置package包名称以及导入依赖的类
package followme.stream
import akka.actor.Actor
import akka.pattern.CircuitBreaker
import com.typesafe.scalalogging.LazyLogging
import followme.stream.TwitterBuilder.twitter
import twitter4j.Status
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.language.postfixOps
case class Retweet(status: Status)
class SerialRetweeter extends Actor with LazyLogging {
override def receive: Receive = {
case Retweet(status) => breaker.withSyncCircuitBreaker {
twitter.retweetStatus(status.getId)
}
}
private val breaker = {
new CircuitBreaker(
context.system.scheduler,
maxFailures = 2,
callTimeout = 10 seconds,
resetTimeout = 50 minutes
).onOpen(notifyMeOnOpen())
}
private def notifyMeOnOpen() = logger.warn("Threshold reach detected")
}
示例6: TopicProducerModule
//设置package包名称以及导入依赖的类
package play.modules
import akka.Done
import akka.actor.ActorSystem
import akka.kafka.ProducerSettings
import akka.kafka.scaladsl.Producer
import akka.pattern.CircuitBreaker
import akka.stream.Materializer
import akka.stream.scaladsl.{ Sink, Source }
import com.google.inject.{ AbstractModule, Provides }
import com.sksamuel.avro4s.RecordFormat
import org.apache.avro.generic.GenericRecord
import org.apache.kafka.clients.producer.ProducerRecord
import scala.concurrent.{ ExecutionContext, Future }
class TopicProducerModule extends AbstractModule {
override def configure(): Unit = {
@Provides
def kafkaProducerProvider(cb: CircuitBreaker)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext): TopicProducer = {
new DefaultTopicProducerModule(cb)(system, mat, ec)
}
}
}
trait TopicProducer {
def produce[A: RecordFormat](topic: String, key: String, value: A): Future[Unit]
}
class DefaultTopicProducerModule(cb: CircuitBreaker)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext) extends TopicProducer {
val producerSettings: ProducerSettings[String, GenericRecord] =
ProducerSettings[String, GenericRecord](system, None, None)
val sink: Sink[ProducerRecord[String, GenericRecord], Future[Done]] =
Producer.plainSink(producerSettings)
def produce[A](topic: String, key: String, value: A)(implicit recordFormat: RecordFormat[A]): Future[Unit] = {
val producerRecord = new ProducerRecord[String, GenericRecord](topic, key, recordFormat.to(value))
cb.withCircuitBreaker(Source.single(producerRecord).runWith(sink)).map(_ => ())
}
}
示例7: CircuitBreakerModule
//设置package包名称以及导入依赖的类
package play.modules
import akka.actor.ActorSystem
import akka.pattern.CircuitBreaker
import com.google.inject.{ AbstractModule, Provides }
import scala.concurrent.ExecutionContext
import scala.concurrent.duration._
class CircuitBreakerModule extends AbstractModule {
override def configure(): Unit = {
@Provides
def circuitBreakerProvider(system: ActorSystem)(implicit ec: ExecutionContext): CircuitBreaker = {
val maxFailures: Int = 3
val callTimeout: FiniteDuration = 1.seconds
val resetTimeout: FiniteDuration = 10.seconds
new CircuitBreaker(system.scheduler, maxFailures, callTimeout, resetTimeout)
}
}
}
示例8: CreatePersonDto
//设置package包名称以及导入依赖的类
package $package$.controller
import java.util.UUID
import javax.inject.Inject
import akka.pattern.CircuitBreaker
import com.sksamuel.avro4s.RecordFormat
import org.slf4j.{ Logger, LoggerFactory }
import play.api.libs.json.{ Format, Json }
import play.api.mvc.{ Action, AnyContent, Controller, Request }
import play.modules.TopicProducer
import scala.concurrent.{ ExecutionContext, Future }
import scala.util.Try
final case class CreatePersonDto(name: String, age: Long, married: Option[Boolean], children: Option[Long])
object CreatePersonDto {
implicit val format = Json.format[CreatePersonDto]
}
final case class PersonCreated(id: String, name: String, age: Long, married: Option[Boolean] = None, children: Long = 0)
case object PersonCreated {
implicit val recordFormat = RecordFormat[PersonCreated]
implicit val format = Json.format[PersonCreated]
}
class PersonController @Inject() (producer: TopicProducer, cb: CircuitBreaker)(implicit ec: ExecutionContext) extends Controller {
val log: Logger = LoggerFactory.getLogger(this.getClass)
def randomId: String = UUID.randomUUID.toString
def entityAs[A: Format](implicit req: Request[AnyContent]): Try[A] =
Try(req.body.asJson.map(_.as[A]).get)
def createPerson = Action.async { implicit req =>
val result = for {
cmd <- Future.fromTry(entityAs[CreatePersonDto])
id = randomId
event = PersonCreated(id, cmd.name, cmd.age, cmd.married, cmd.children.getOrElse(0))
_ <- producer.produce("PersonCreatedAvro", id, event)
} yield Ok(Json.toJson(event))
cb.withCircuitBreaker(result)
}
}