24
24
public class FailsafeWebserver {
25
25
private static final Logger log = LoggerFactory .getLogger (FailsafeWebserver .class );
26
26
27
+ // {{start:breaker}}
28
+ private static final CircuitBreaker CIRCUIT_BREAKER = new CircuitBreaker ()
29
+ // Trigger circuit breaker failure on exceptions or bad requests
30
+ .failIf ((HttpServerExchange exchange , Throwable ex ) -> {
31
+ boolean badRequest = exchange != null && StatusCodes .BAD_REQUEST == exchange .getStatusCode ();
32
+ return badRequest || ex != null ;
33
+ })
34
+ // If 7 out of 10 requests fail Open the circuit
35
+ .withFailureThreshold (7 , 10 )
36
+ // When half open if 3 out of 5 requests succeed close the circuit
37
+ .withSuccessThreshold (3 , 5 )
38
+ // Delay this long before half opening the circuit
39
+ .withDelay (2 , TimeUnit .SECONDS )
40
+ .onClose (() -> log .info ("Circuit Closed" ))
41
+ .onOpen (() -> log .info ("Circuit Opened" ))
42
+ .onHalfOpen (() -> log .info ("Circuit Half-Open" ));
43
+ // {{end:breaker}}
44
+
27
45
// {{start:handlers}}
46
+ // Actual Circuit Breaker Handler
47
+ private static final HttpHandler CIRCUIT_BREAKER_HANDLER =
48
+ new CircuitBreakerHandler (CIRCUIT_BREAKER ,
49
+ FailsafeWebserver ::circuitClosed ,
50
+ FailsafeWebserver ::serverError );
51
+
52
+ // Handler return a 500 server error
28
53
private static final void serverError (HttpServerExchange exchange ) {
29
54
exchange .setStatusCode (StatusCodes .INTERNAL_SERVER_ERROR );
30
55
Exchange .body ().sendText (exchange , "500 - Internal Server Error" );
@@ -43,29 +68,6 @@ private static final void circuitClosed(HttpServerExchange exchange) {
43
68
Exchange .body ().sendText (exchange , "Circuit is open everything is functioning properly." );
44
69
}
45
70
}
46
-
47
- private static final HttpHandler CIRCUIT_BREAKER_HANDLER ;
48
- static {
49
- CircuitBreaker breaker = new CircuitBreaker ()
50
- // Trigger circuit breaker failure on exceptions or bad requests
51
- .failIf ((HttpServerExchange exchange , Throwable ex ) -> {
52
- return (exchange != null && StatusCodes .BAD_REQUEST == exchange .getStatusCode ())
53
- || ex != null ;
54
- })
55
- // If 7 out of 10 requests fail Open the circuit
56
- .withFailureThreshold (7 , 10 )
57
- // When half open if 3 out of 5 requests succeed close the circuit
58
- .withSuccessThreshold (3 , 5 )
59
- // Delay this long before half opening the circuit
60
- .withDelay (2 , TimeUnit .SECONDS )
61
- .onClose (() -> log .info ("Circuit Closed" ))
62
- .onOpen (() -> log .info ("Circuit Opened" ))
63
- .onHalfOpen (() -> log .info ("Circuit Half-Open" ));
64
-
65
- CIRCUIT_BREAKER_HANDLER = new CircuitBreakerHandler (breaker ,
66
- FailsafeWebserver ::circuitClosed ,
67
- FailsafeWebserver ::serverError );
68
- }
69
71
// {{end:handlers}}
70
72
71
73
// {{start:request}}
0 commit comments