Ukuhlobisa Ungafundisa indlela yokwenza izivakashi zakho ze-microservice ezihambayo usebenzisa isampula ye-Circuit Breaker nge Waze I-demo ephelele, i-step-by-step orders, izifundo ze-class-by-class, imiphumela ye-sample, izicelo ze-real-world, kanye namasipho yokukhiqiza. Resilience4j Spring Boot Why This Matters Yini lokhu kubaluleke Ngama-system e-distributed, inkonzo enhle e-downstream ingangena futhi inikeza isixazululo se-system jikelele. imikhiqizo: Circuit Breaker Ukubuyekeza ukuxhumana okufakiwe, Hlola ukulayisha imibuzo ku-imeyili (ukuvimbela ukuchithwa kwezimpahla), Ukuguqulwa kwe-Fallback Response, Okwangoku ukuhlola ukuxhumana kanye nokuguqulwa ukusebenza okuqhubekayo ngesikhathi esihle. Kuyinto ukunciphisa izinga lokushisa, ukhuseleko i-thread pools, ukugcina ikhono lomsebenzisi enhle, nokuvimbela ama-retry storms. Demo Summary (What You Have) Ukubuyekezwa kwe-Demo (What You Have) I-Double-Service Maven I-Demo Yomphakathi: (port ) — simple REST provider that intentionally fails intermittently. hello-service 8081 Okokuqala Point GET /api/hello (port ) — calls hello-service using RestTemplate and is protected by with a fallback. client-service 8080 Resilience4j @CircuitBreaker Okokuqala Point GET /api/get-message Ukulungiselela ( ) hello-service and client-service Ukuhlolwa GET http://localhost:8080/api/get-message I-Diagram ye-Architecture Kuyinto uchungechunge omncane, okuhlobene, efanelekayo yokucoca i-diagram Files & Code: Class-By-Class Explanation Files & Code: Class-by-Class Ukucaciswa hello-service I-HelloServiceApplication.java Standard bootstrap class. @SpringBootApplication HelloController.java @RestController public class HelloController { private static int counter = 0; @GetMapping("/api/hello") public String sayHello() { counter++; // simulate intermittent failure: fail on every 3rd request if (counter % 3 == 0) { throw new RuntimeException("Simulated failure from Hello-Service!"); } return "Hello from Hello-Service! (count=" + counter + ")"; } } Uhlelo le-Controller usebenzisa RuntimeException ku-call periodic ukuze ikhoyile imiphumela emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni emzimbeni. Explanation: client-service I-ClientServiceApplication.java I-Standard Spring Boot isigaba esikhulu. Akukho ukulungiselela esizayo. AppConfig.java @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } Inikeza i-RestTemplate bean eyodwa. Qinisekisa ukuthi i-RestTemplate kuyinto i-Spring bean ukuze ama-AOP/i-resilience proxies zokusebenza ngokushesha. Explanation: HelloClientService.java @Service public class HelloClientService { private final RestTemplate restTemplate; @Value("${hello.service.url}") private String helloServiceUrl; public HelloClientService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @CircuitBreaker(name = "helloService", fallbackMethod = "fallbackHello") public String getHelloMessage() { System.out.println("Calling hello service: " + helloServiceUrl); return restTemplate.getForObject(helloServiceUrl, String.class); } public String fallbackHello(Throwable t) { System.out.println("Fallback triggered: " + t); return "Hello Service is currently unavailable. Please try again later."; } } Explanation (crucial bits) @CircuitBreaker(name = "helloService", fallbackMethod = "fallbackHello") wraps the getHelloMessage() call in a circuit breaker. The name links to configuration properties. fallbackHello(Throwable t) is called when the call fails according to the breaker rules. The fallback must: o Be in the same class o Have the same return type o Accept the original method parameters (none here) and a final Throwable parameter (or Exception/Throwable compatible with thrown exceptions) Important: The method must be public, and the class must be a Spring bean (@Service), so proxy-based AOP works. ClientController.java @RestController public class ClientController { private final HelloClientService helloClientService; public ClientController(HelloClientService helloClientService) { this.helloClientService = helloClientService; } @GetMapping("/api/get-message") public String getMessage() { return helloClientService.getHelloMessage(); } } I-Controller Simple I-Delegate Ukuze Ngokwenza lokhu, ibhalansi ivela nge-proxy lapho i-circuit breaker isetshenziswe. Explanation: HelloClientService Configuration Used (client-service application.properties) Isakhiwo esebenzayo (i-client-service application.properties) I-key configuration esetshenziselwa ku-demo server.port=8080 spring.application.name=client-service hello.service.url=http://localhost:8081/api/hello resilience4j.circuitbreaker.instances.helloService.registerHealthIndicator=true resilience4j.circuitbreaker.instances.helloService.slidingWindowSize=5 resilience4j.circuitbreaker.instances.helloService.minimumNumberOfCalls=2 resilience4j.circuitbreaker.instances.helloService.failureRateThreshold=50 resilience4j.circuitbreaker.instances.helloService.waitDurationInOpenState=10s logging.level.io.github.resilience4j.circuitbreaker=DEBUG Meaning of important properties slidingWindowSize: Inani izivakashi ze-broker monitors ukuze uthole inqubo yokungasebenzi. MinimumNumberOfCalls: Izivumelwano ezingenalutho ezingenalutho ngaphambi kokushintshwa kwama-failure rate. I-failureRateThreshold: I-percentage ye-failures (isib. i-50) yokufaka isiteshi. waitDurationInOpenState: isikhathi eside esifundeni esifundeni esifundeni esifundeni esifundeni esifundeni. RegisterHealthIndicator: ukunikezela umoya we-breaker nge-aktuator. I-Step-by-Step Run & Imiphumela Yokusho Ukuqala Izinsiza Okokuqala-Hello-Service Visit: http://localhost:8081/api/hello → "Hello kusukela Hello-Service!" (noma uketshezi isizukulwane isizukulwane) Returns Ukushaja i-Customer Service Visit: http://localhost:8080/api/get-message Test Scenarios & Outputs Ukuhlolwa Scenarios & Outputs Scenario A — Hello-Service Healthy Yenza isicelo GET http://localhost:8080/api/get-message Ikhasimende Calling hello service: http://localhost:8081/api/hello 2025-11-13T11:58:23.366+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-8] i.g.r.c.i.CircuitBreakerStateMachine : CircuitBreaker 'helloService' succeeded: 2025-11-13T11:58:23.366+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-8] i.g.r.c.i.CircuitBreakerStateMachine : Event SUCCESS published: 2025-11-13T11:58:23.366634+05:30[Asia/Calcutta]: CircuitBreaker 'helloService' recorded a successful call. Elapsed time: 15 ms Response Hello from Hello-Service! (count=4) Scenario B — Hello-Service Intermittent Failures Uma uqhagamshelane ngokuvamile futhi i-hello-service ihamba Ngezinye izicelo: RuntimeException ● Ukusabela okuphumelela: I-client ivumela isitimela se-hello. ● Uma isivumelwano esilandelayo ivumela i-HTTP 500/exception: o Resilience4j records the failure. o If failure rate exceeds threshold (e.g., 50% over sliding window), the Circuit becomes **OPEN**. o While OPEN, calls are short-circuited; **fallbackHello**() is immediately executed — no network call. \n **Client response while fallback active** Client Response while active Response Hello Service is currently unavailable. Please try again later. Sample client log sequence Calling hello service: http://localhost:8081/api/hello 2025-11-13T12:00:55.842+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-1] i.g.r.c.i.CircuitBreakerStateMachine : CircuitBreaker 'helloService' recorded an exception as failure: Scenario C — Recovery Ngemva UkulungiselelaUkulungiselela (10s): UkulungiselelaUkulungiselela I-Circuit ivuka ku-HALF_OPEN: Izincwajana ezimbalwa zokusebenza. Uma izivakashi zokusebenza, i-broker ISIFULEKA futhi i-traffic ebonakalayo isivakashi. Uma izivivinyo zihlukile, i-Breaker iyahamba ku-OPEN. Real-World Use Cases I-Real-World Uses Case I-Payment Integration - I-Checkout Service enikeza i-API yebhanki ye-external: Uma i-API yebhanki ivula / ivula, i-circuit breaker ivumela isitimela esebenzayo futhi ivimbela ama-retry storms. I-Third-party rate-limited APIs - I-API nge-call-per-second limited - uma ama-limits eyenziwe, isiteshi ivula ukuze akuyona ukufinyelela kwama-quota ngaphezulu; i-fallback ivumela idatha e-cache. I-Microservice Chains ku-Enterprise - I-Service A ivumela i-B, okuyinto ivumela i-C. Uma i-C iyatholakala, i-Open Breakers zihlanganisa i-B ne-A, ukuvimbela ukuhlaziywa kwe-system jikelele. Izici ye-Feature ne-Graceful Degradation - Uma inkonzo ye-Feature e-Non-Critical isixazululo, ukuguqulela imiphumela enhle ukuze ukugcina umsebenzi wokugqibela (isib. Ukuguqulwa kwe-Product List ngaphandle kwe-Recommendations). Advantages & Business Value Izinzuzo & I-Business Value I-Fault Isolation - ivimbela isisindo esihle esihlalweni esihlalweni. Ukusabela ngokushesha - ukuphazamiseka ngokushesha kunokufaka isikhathi eside. I-Degradation ye-Graceful - inikeza imibuzo ye-fallback kunokuba i-disruptions ephelele. Ukuvikelwa kwamakhemikhali-ukuvimbela ukuchithwa kwe-CPU, ama-threads, ne-network. Ukuguqulwa okuzenzakalelayo - okuzenzakalelayo kwangaphambili lapho umngciwane wahlukanisa. Ukuhlobisa - izimo ze-breaker kanye ne-metric zingatholakala nge-Aktuator futhi zihlanganiswe. Sample logs you’ll see (realistic) Calling hello service: http://localhost:8081/api/hello 2025-11-13T12:00:55.842+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-1] i.g.r.c.i.CircuitBreakerStateMachine : CircuitBreaker 'helloService' recorded an exception as failure 2025-11-13T12:00:55.847+05:30 DEBUG 32692 --- [client-service] [nio-8080-exec-1] i.g.r.c.i.CircuitBreakerStateMachine : Event ERROR published: 2025-11-13T12:00:55.847908200+05:30[Asia/Calcutta]: CircuitBreaker 'helloService' recorded an error: 'org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 : "{"timestamp":"2025-11-13T06:30:55.842+00:00","status":500,"error":"Internal Server Error","path":"/api/hello"}"'. Elapsed time: 8 ms Fallback triggered: org.springframework.web.client.HttpServerErrorException$InternalServerError: 500 : "{"timestamp":"2025-11-13T06:30:55.842+00:00","status":500,"error":"Internal Server Error","path":"/api/hello"}"