resilience4j-circuit-breaker: add state-transition, slow-call, TimeLimiter, ignoreExceptions and RateLimiter tests on Boot 4.1.2

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b74uRrp2Tiu2PngyuY
This commit is contained in:
2026-11-12 11:00:26 +05:30
co-authored by Claude Sonnet 5.5
parent ae696369ba
commit fe3fc689a6
14 changed files with 520 additions and 7 deletions
@@ -0,0 +1,11 @@
package com.ankurm.resilience.r4j;
/**
* A business outcome ("no such product"), not a sign the dependency is unhealthy.
* The breaker instance lookupIgnored lists it under ignoreExceptions.
*/
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(String id) {
super("no product " + id);
}
}
@@ -0,0 +1,27 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.stereotype.Service;
/**
* Two deliberately wrong fallbacks: pay() names a fallback whose parameters do not match
* (Integer, Throwable instead of String), payMissing() names a fallback that does not exist.
* Used only by ClaimsCheckTest to show what each mistake looks like.
*/
@Service
public class R4jBadFallbackService {
@CircuitBreaker(name = "lookupCounted", fallbackMethod = "wrong")
public String pay(String orderId) {
throw new IllegalStateException("downstream down");
}
@CircuitBreaker(name = "lookupCounted", fallbackMethod = "doesNotExist")
public String payMissing(String orderId) {
throw new IllegalStateException("downstream down");
}
private String wrong(Integer orderId, Throwable ex) {
return "never reached";
}
}
@@ -0,0 +1,23 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.stereotype.Service;
/**
* The same "not found" method behind two breakers that differ in one line of YAML:
* lookupCounted counts ProductNotFoundException as a failure (the default),
* lookupIgnored lists it under ignoreExceptions so it counts as neither success nor failure.
*/
@Service
public class R4jLookupService {
@CircuitBreaker(name = "lookupCounted")
public String findCounted(String id) {
throw new ProductNotFoundException(id);
}
@CircuitBreaker(name = "lookupIgnored")
public String findIgnored(String id) {
throw new ProductNotFoundException(id);
}
}
@@ -0,0 +1,22 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import org.springframework.stereotype.Service;
/**
* In-process rate limiter: 3 calls per 1s period, no waiting (timeoutDuration=0).
* Config: resilience4j.ratelimiter.instances.searchApi.
*/
@Service
public class R4jRateLimiterService {
@RateLimiter(name = "searchApi", fallbackMethod = "tooMany")
public String search(String q) {
return "results:" + q;
}
private String tooMany(String q, RequestNotPermitted ex) {
return "RATE_LIMITED:" + q;
}
}
@@ -0,0 +1,23 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.stereotype.Service;
/**
* A call that always SUCCEEDS but can be slow. The breaker "slowBreaker" has
* slowCallDurationThreshold=200ms and slowCallRateThreshold=50, so it opens on latency alone,
* with a failure rate of zero. Config: resilience4j.circuitbreaker.instances.slowBreaker.
*/
@Service
public class R4jSlowCallService {
@CircuitBreaker(name = "slowBreaker", fallbackMethod = "fallback")
public String call(String id, long sleepMillis) throws InterruptedException {
Thread.sleep(sleepMillis);
return "ok:" + id;
}
private String fallback(String id, long sleepMillis, Throwable ex) {
return "FALLBACK:" + id + ":" + ex.getClass().getSimpleName();
}
}
@@ -0,0 +1,61 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Resilience4j's TimeLimiter. It only works on methods that return a CompletableFuture
* (or a reactive type) because it has to be able to stop waiting for something that is still
* running on another thread. Config: resilience4j.timelimiter.instances.slowLookup.
*/
@Service
public class R4jTimeLimiterService {
/** TimeLimiter alone: a call slower than 500ms is answered by the fallback. */
@TimeLimiter(name = "slowLookup", fallbackMethod = "timedOut")
public CompletableFuture<String> lookup(String id, long sleepMillis) {
return CompletableFuture.supplyAsync(() -> slow(id, sleepMillis));
}
/**
* TimeLimiter plus CircuitBreaker: every timeout is recorded as a failure by the breaker,
* so a dependency that is merely slow will eventually open the circuit.
*/
@CircuitBreaker(name = "timeoutBreaker", fallbackMethod = "breakerFallback")
@TimeLimiter(name = "slowLookup")
public CompletableFuture<String> guardedLookup(String id, long sleepMillis) {
return CompletableFuture.supplyAsync(() -> slow(id, sleepMillis));
}
/** Counts how many slow calls ran all the way to the end, whether or not anyone was still waiting. */
private final AtomicInteger finishedWork = new AtomicInteger();
/** A method, not a public field: this bean is wrapped in a proxy, and a field read on the proxy is not the real field. */
public AtomicInteger finishedWork() {
return finishedWork;
}
private String slow(String id, long sleepMillis) {
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
finishedWork.incrementAndGet();
return "found:" + id;
}
private CompletableFuture<String> timedOut(String id, long sleepMillis, TimeoutException ex) {
return CompletableFuture.completedFuture("TIMED_OUT:" + id);
}
private CompletableFuture<String> breakerFallback(String id, long sleepMillis, Throwable ex) {
return CompletableFuture.completedFuture("FALLBACK:" + id + ":" + ex.getClass().getSimpleName());
}
}
@@ -30,6 +30,46 @@ resilience4j:
automaticTransitionFromOpenToHalfOpenEnabled: true
recordExceptions:
- com.ankurm.resilience.FlakyDownstream$DownstreamUnavailableException
# Opens on latency alone: every call succeeds, but 2 of 4 take longer than 200ms.
slowBreaker:
slidingWindowType: COUNT_BASED
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
slowCallDurationThreshold: 200ms
slowCallRateThreshold: 50
waitDurationInOpenState: 5s
# Sits behind @TimeLimiter: each timeout is one recorded failure.
timeoutBreaker:
slidingWindowType: COUNT_BASED
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
waitDurationInOpenState: 5s
# Identical pair; the only difference is ignoreExceptions.
lookupCounted:
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
waitDurationInOpenState: 5s
lookupIgnored:
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
waitDurationInOpenState: 5s
ignoreExceptions:
- com.ankurm.resilience.r4j.ProductNotFoundException
timelimiter:
instances:
slowLookup:
timeoutDuration: 500ms
cancelRunningFuture: true
ratelimiter:
instances:
searchApi:
limitForPeriod: 3
limitRefreshPeriod: 1s
timeoutDuration: 0
bulkhead:
instances:
slowOp: