2424public class FailsafeWebserver {
2525 private static final Logger log = LoggerFactory .getLogger (FailsafeWebserver .class );
2626
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+
2745 // {{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
2853 private static final void serverError (HttpServerExchange exchange ) {
2954 exchange .setStatusCode (StatusCodes .INTERNAL_SERVER_ERROR );
3055 Exchange .body ().sendText (exchange , "500 - Internal Server Error" );
@@ -43,29 +68,6 @@ private static final void circuitClosed(HttpServerExchange exchange) {
4368 Exchange .body ().sendText (exchange , "Circuit is open everything is functioning properly." );
4469 }
4570 }
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- }
6971 // {{end:handlers}}
7072
7173 // {{start:request}}
0 commit comments