|
| 1 | +packagecom.stubbornjava.examples.failsafe; |
| 2 | + |
| 3 | +importjava.io.IOException; |
| 4 | +importjava.util.concurrent.Executors; |
| 5 | +importjava.util.concurrent.ScheduledExecutorService; |
| 6 | +importjava.util.concurrent.TimeUnit; |
| 7 | + |
| 8 | +importorg.slf4j.Logger; |
| 9 | +importorg.slf4j.LoggerFactory; |
| 10 | + |
| 11 | +importcom.stubbornjava.common.HttpClient; |
| 12 | +importcom.stubbornjava.common.undertow.Exchange; |
| 13 | +importcom.stubbornjava.common.undertow.SimpleServer; |
| 14 | +importcom.stubbornjava.common.undertow.handlers.CircuitBreakerHandler; |
| 15 | +importcom.stubbornjava.common.undertow.handlers.CustomHandlers; |
| 16 | + |
| 17 | +importio.undertow.server.HttpHandler; |
| 18 | +importio.undertow.server.HttpServerExchange; |
| 19 | +importio.undertow.util.StatusCodes; |
| 20 | +importnet.jodah.failsafe.CircuitBreaker; |
| 21 | +importokhttp3.HttpUrl; |
| 22 | +importokhttp3.Request; |
| 23 | + |
| 24 | +publicclassFailsafeWebserver { |
| 25 | +privatestaticfinalLoggerlog =LoggerFactory.getLogger(FailsafeWebserver.class); |
| 26 | + |
| 27 | +// {{start:handlers}} |
| 28 | +privatestaticfinalvoidserverError(HttpServerExchangeexchange) { |
| 29 | +exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR); |
| 30 | +Exchange.body().sendText(exchange,"500 - Internal Server Error"); |
| 31 | + } |
| 32 | + |
| 33 | +// This handler helps simulate errors, bad requests, and successful requests. |
| 34 | +privatestaticfinalvoidcircuitClosed(HttpServerExchangeexchange) { |
| 35 | +booleanerror =Exchange.queryParams().queryParamAsBoolean(exchange,"error").orElse(false); |
| 36 | +booleanexception =Exchange.queryParams().queryParamAsBoolean(exchange,"exception").orElse(false); |
| 37 | +if (error) { |
| 38 | +exchange.setStatusCode(StatusCodes.BAD_REQUEST); |
| 39 | +Exchange.body().sendText(exchange,"Bad Request"); |
| 40 | + }elseif (exception) { |
| 41 | +thrownewRuntimeException("boom"); |
| 42 | + }else { |
| 43 | +Exchange.body().sendText(exchange,"Circuit is open everything is functioning properly."); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | +privatestaticfinalHttpHandlerCIRCUIT_BREAKER_HANDLER; |
| 48 | +static { |
| 49 | +CircuitBreakerbreaker =newCircuitBreaker() |
| 50 | +// Trigger circuit breaker failure on exceptions or bad requests |
| 51 | + .failIf((HttpServerExchangeexchange,Throwableex) -> { |
| 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 =newCircuitBreakerHandler(breaker, |
| 66 | +FailsafeWebserver::circuitClosed, |
| 67 | +FailsafeWebserver::serverError); |
| 68 | + } |
| 69 | +// {{end:handlers}} |
| 70 | + |
| 71 | +// {{start:request}} |
| 72 | +privatestaticvoidrequest(booleanerror,booleanexception) { |
| 73 | +HttpUrlurl =HttpUrl.parse("http://localhost:8080") |
| 74 | + .newBuilder() |
| 75 | + .addQueryParameter("error",String.valueOf(error)) |
| 76 | + .addQueryParameter("exception",String.valueOf(exception)) |
| 77 | + .build(); |
| 78 | + |
| 79 | +Requestrequest =newRequest.Builder().get().url(url).build(); |
| 80 | +try { |
| 81 | +log.info(HttpClient.globalClient().newCall(request).execute().body().string()); |
| 82 | + }catch (IOExceptione) { |
| 83 | +e.printStackTrace(); |
| 84 | + } |
| 85 | + } |
| 86 | +// {{end:request}} |
| 87 | + |
| 88 | +// {{start:main}} |
| 89 | +publicstaticvoidmain(String[]args) { |
| 90 | + |
| 91 | +HttpHandlerexceptionHandler = |
| 92 | +CustomHandlers.exception(CIRCUIT_BREAKER_HANDLER) |
| 93 | + .addExceptionHandler(Throwable.class,FailsafeWebserver::serverError); |
| 94 | + |
| 95 | +SimpleServerserver =SimpleServer.simpleServer(exceptionHandler); |
| 96 | +server.start(); |
| 97 | + |
| 98 | + |
| 99 | +// Warm-up the circuit breaker it needs to hit at least max executions |
| 100 | +// Before it will reject anything. This will make that easier. |
| 101 | +for (inti =0;i <10;i++) { |
| 102 | +request(false,false); |
| 103 | + } |
| 104 | +ScheduledExecutorServiceschedExec =Executors.newScheduledThreadPool(1); |
| 105 | + |
| 106 | +// A simple request that should always succeed |
| 107 | +schedExec.scheduleAtFixedRate(() ->request(false,false),0,500,TimeUnit.MILLISECONDS); |
| 108 | + |
| 109 | +// Send a batch of 15 bad requests to trigger the circuit breaker |
| 110 | +Runnableerrors = () -> { |
| 111 | +log.info("Executing bad requests!"); |
| 112 | +for (inti =0;i <15;i++) { |
| 113 | +request(true,false); |
| 114 | + } |
| 115 | + }; |
| 116 | +schedExec.schedule(errors,1,TimeUnit.SECONDS); |
| 117 | + |
| 118 | +// Send a batch of 15 requests that throw exceptions |
| 119 | +Runnableexceptions = () -> { |
| 120 | +log.info("Executing requests that throw exceptions!"); |
| 121 | +for (inti =0;i <15;i++) { |
| 122 | +request(false,true); |
| 123 | + } |
| 124 | + }; |
| 125 | +schedExec.schedule(exceptions,5,TimeUnit.SECONDS); |
| 126 | + } |
| 127 | +// {{end:main}} |
| 128 | +} |