本文整理汇总了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?
}
}
开发者ID:zalando-incubator,项目名称:hutmann,代码行数:21,代码来源:CircuitBreakerFactory.scala
示例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")
}
}
}
}
}
开发者ID:code-star,项目名称:akka-http-course,代码行数:51,代码来源:Main.scala
示例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)
}
开发者ID:bahadley,项目名称:akka-slick-demo,代码行数:40,代码来源:Ocb.scala
示例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))
})
}
}
开发者ID:dazito,项目名称:LearningAkkaScalaServer,代码行数:47,代码来源:Main.scala
示例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")
}
开发者ID:adericbourg,项目名称:followme-twitter-poc,代码行数:34,代码来源:retweet.scala
示例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(_ => ())
}
}
开发者ID:dnvriend,项目名称:play-kafka-producer-seed.g8,代码行数:42,代码来源:TopicProducerModule.scala
示例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)
}
}
}
开发者ID:dnvriend,项目名称:play-kafka-producer-seed.g8,代码行数:21,代码来源:CircuitBreakerModule.scala
示例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)
}
}
开发者ID:dnvriend,项目名称:play-kafka-producer-seed.g8,代码行数:45,代码来源:PersonController.scala
注:本文中的akka.pattern.CircuitBreaker类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论