forked from ReactiveDesignPatterns/CodeSamples
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathStorageComponent.scala
More file actions
45 lines (34 loc) · 1.25 KB
/
StorageComponent.scala
File metadata and controls
45 lines (34 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
* Copyright (c) 2018 https://www.reactivedesignpatterns.com/
*
* Copyright (c) 2018 https://rdp.reactiveplatform.xyz/
*
*/
package chapter12
import akka.actor.ActorSystem
import akka.pattern.{ CircuitBreaker, CircuitBreakerOpenException }
import scala.concurrent.{ Future, TimeoutException }
// 代码清单 12-1
// Listing 12.1 Using a circuit breaker to give a failed component time to recover
class StorageComponent(system: ActorSystem) {
// #snip
private object StorageFailed extends RuntimeException
import akka.rdpextras.ExecutionContexts.sameThreadExecutionContext
private def sendToStorage(job: Job): Future[StorageStatus] = {
val f: Future[StorageStatus] = ??? //...
f.map {
case StorageStatus.Failed => throw StorageFailed
case other => other
}
}
import scala.concurrent.duration._
private val breaker = CircuitBreaker(system.scheduler, 5, 300.millis, 30.seconds)
def persist(job: Job): Future[StorageStatus] = {
breaker.withCircuitBreaker(sendToStorage(job)).recover {
case StorageFailed => StorageStatus.Failed
case _: TimeoutException => StorageStatus.Unknown
case _: CircuitBreakerOpenException => StorageStatus.Failed
}
}
// #snip
}