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:
@@ -17,9 +17,9 @@ to stay independently reproducible from its own module.
|
|||||||
|
|
||||||
| Component | Version | Notes |
|
| Component | Version | Notes |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| JDK | 25 (Temurin 25.0.4.1+1) | latest LTS |
|
| JDK | 25 (Temurin 25.0.5+8) | latest LTS |
|
||||||
| Spring Boot | 4.1.1 | latest GA at time of writing; 4.2.0-M1 exists but is a milestone |
|
| Spring Boot | 4.1.2 | latest GA at time of writing; 4.2.0-RC2 exists but is a release candidate |
|
||||||
| Spring Framework | 7.0.9 | latest GA; 7.1.0-M1 exists but is a milestone |
|
| Spring Framework | 7.0.10 | managed by Boot 4.1.2 |
|
||||||
| Resilience4j | 2.4.0 (`resilience4j-spring-boot4`) | depends internally on `resilience4j-spring6`, not a "spring7" module — see [docs/01](docs/01-two-resilience-stacks.md) |
|
| Resilience4j | 2.4.0 (`resilience4j-spring-boot4`) | depends internally on `resilience4j-spring6`, not a "spring7" module — see [docs/01](docs/01-two-resilience-stacks.md) |
|
||||||
|
|
||||||
## Quickstart
|
## Quickstart
|
||||||
@@ -47,6 +47,13 @@ local cache); `-o` works for subsequent builds.
|
|||||||
| `@ConcurrencyLimit` REJECT policy | same | same | [`04b`](docs/output/04b-concurrencylimit-reject.txt) |
|
| `@ConcurrencyLimit` REJECT policy | same | same | [`04b`](docs/output/04b-concurrencylimit-reject.txt) |
|
||||||
| Resilience4j `@Bulkhead` (bounded wait) for comparison | [`R4jBulkheadService`](src/main/java/com/ankurm/resilience/r4j/R4jBulkheadService.java) | same | [`04c`](docs/output/04c-r4j-bulkhead-comparison.txt) |
|
| Resilience4j `@Bulkhead` (bounded wait) for comparison | [`R4jBulkheadService`](src/main/java/com/ankurm/resilience/r4j/R4jBulkheadService.java) | same | [`04c`](docs/output/04c-r4j-bulkhead-comparison.txt) |
|
||||||
| Real `/actuator/health` + `/actuator/circuitbreakers` with a breaker OPEN | [`R4jPaymentService`](src/main/java/com/ankurm/resilience/r4j/R4jPaymentService.java) | [`ActuatorHealthTest`](src/test/java/com/ankurm/resilience/r4j/ActuatorHealthTest.java) | [`05`](docs/output/05-actuator-health-tripped.txt) |
|
| Real `/actuator/health` + `/actuator/circuitbreakers` with a breaker OPEN | [`R4jPaymentService`](src/main/java/com/ankurm/resilience/r4j/R4jPaymentService.java) | [`ActuatorHealthTest`](src/test/java/com/ankurm/resilience/r4j/ActuatorHealthTest.java) | [`05`](docs/output/05-actuator-health-tripped.txt) |
|
||||||
|
| State transitions through the event publisher (`CLOSED -> OPEN -> HALF_OPEN -> OPEN`) | [`R4jPaymentService`](src/main/java/com/ankurm/resilience/r4j/R4jPaymentService.java) | [`StateTransitionsTest`](src/test/java/com/ankurm/resilience/r4j/StateTransitionsTest.java) | written to `target/transcripts/` by the test |
|
||||||
|
| Testing without sleeping: force the breaker state | same | same | same |
|
||||||
|
| Slow-call rate opens the breaker with zero failures | [`R4jSlowCallService`](src/main/java/com/ankurm/resilience/r4j/R4jSlowCallService.java) | [`LatencyAndTimeoutTest`](src/test/java/com/ankurm/resilience/r4j/LatencyAndTimeoutTest.java) | same |
|
||||||
|
| `@TimeLimiter`, alone and combined with `@CircuitBreaker` | [`R4jTimeLimiterService`](src/main/java/com/ankurm/resilience/r4j/R4jTimeLimiterService.java) | same | same |
|
||||||
|
| `ignoreExceptions` for business errors | [`R4jLookupService`](src/main/java/com/ankurm/resilience/r4j/R4jLookupService.java) | [`IgnoreExceptionsAndRateLimiterTest`](src/test/java/com/ankurm/resilience/r4j/IgnoreExceptionsAndRateLimiterTest.java) | same |
|
||||||
|
| `@RateLimiter` | [`R4jRateLimiterService`](src/main/java/com/ankurm/resilience/r4j/R4jRateLimiterService.java) | same | same |
|
||||||
|
| What happens to a call the `@TimeLimiter` gave up on; wrong or missing fallback methods; the library defaults | [`R4jBadFallbackService`](src/main/java/com/ankurm/resilience/r4j/R4jBadFallbackService.java) | [`ClaimsCheckTest`](src/test/java/com/ankurm/resilience/r4j/ClaimsCheckTest.java) | same |
|
||||||
|
|
||||||
## Endpoints (from `scripts/run.sh`)
|
## Endpoints (from `scripts/run.sh`)
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
<parent>
|
<parent>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
<artifactId>spring-boot-starter-parent</artifactId>
|
||||||
<version>4.1.1</version>
|
<version>4.1.2</version>
|
||||||
<relativePath/>
|
<relativePath/>
|
||||||
</parent>
|
</parent>
|
||||||
|
|
||||||
|
|||||||
+11
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -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";
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+61
@@ -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
|
automaticTransitionFromOpenToHalfOpenEnabled: true
|
||||||
recordExceptions:
|
recordExceptions:
|
||||||
- com.ankurm.resilience.FlakyDownstream$DownstreamUnavailableException
|
- 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:
|
bulkhead:
|
||||||
instances:
|
instances:
|
||||||
slowOp:
|
slowOp:
|
||||||
|
|||||||
@@ -17,12 +17,21 @@ public final class Transcript {
|
|||||||
private final StringBuilder buf = new StringBuilder();
|
private final StringBuilder buf = new StringBuilder();
|
||||||
private final Path outFile;
|
private final Path outFile;
|
||||||
|
|
||||||
private Transcript(String fileName) {
|
private Transcript(Path outFile) {
|
||||||
this.outFile = Paths.get("docs/output", fileName);
|
this.outFile = outFile;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static Transcript start(String fileName, String header) {
|
public static Transcript start(String fileName, String header) {
|
||||||
Transcript t = new Transcript(fileName);
|
return begin(Paths.get("docs/output", fileName), header);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same as start(), but writes under target/transcripts so a plain `mvn test` adds nothing to the source tree. */
|
||||||
|
public static Transcript scratch(String fileName, String header) {
|
||||||
|
return begin(Paths.get("target/transcripts", fileName), header);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Transcript begin(Path file, String header) {
|
||||||
|
Transcript t = new Transcript(file);
|
||||||
t.line(header);
|
t.line(header);
|
||||||
t.line("=".repeat(header.length()));
|
t.line("=".repeat(header.length()));
|
||||||
return t;
|
return t;
|
||||||
|
|||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
package com.ankurm.resilience.r4j;
|
||||||
|
|
||||||
|
import com.ankurm.resilience.Transcript;
|
||||||
|
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/** Output: 13-abandoned-work.txt, 14-bad-fallback-signature.txt, 15-defaults.txt. */
|
||||||
|
@SpringBootTest
|
||||||
|
@DirtiesContext
|
||||||
|
class ClaimsCheckTest {
|
||||||
|
|
||||||
|
@Autowired R4jTimeLimiterService timeLimited;
|
||||||
|
@Autowired R4jBadFallbackService bad;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void timeLimiterStopsWaitingButTheWorkStillFinishes() throws Exception {
|
||||||
|
Transcript t = Transcript.scratch("13-abandoned-work.txt", "What happens to the call the TimeLimiter gave up on?");
|
||||||
|
timeLimited.finishedWork().set(0);
|
||||||
|
String r = timeLimited.lookup("z", 1500).get();
|
||||||
|
t.line("caller got: " + r);
|
||||||
|
t.line("finished work right after timeout: " + timeLimited.finishedWork().get());
|
||||||
|
Thread.sleep(1500);
|
||||||
|
t.line("finished work 1.5s later: " + timeLimited.finishedWork().get());
|
||||||
|
assertThat(r).isEqualTo("TIMED_OUT:z");
|
||||||
|
assertThat(timeLimited.finishedWork().get()).isEqualTo(1);
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mismatchedFallbackSignatureFailsAtCallTime() {
|
||||||
|
Transcript t = Transcript.scratch("14-bad-fallback-signature.txt", "Fallback whose parameters do not match the method");
|
||||||
|
t.line("application context started without complaint; the mistakes only show on a call");
|
||||||
|
t.blank();
|
||||||
|
Throwable mismatched = null;
|
||||||
|
try { bad.pay("o-1"); } catch (Throwable e) { mismatched = e; }
|
||||||
|
t.line("fallback exists, wrong parameters -> " + mismatched.getClass().getName() + ": " + mismatched.getMessage());
|
||||||
|
Throwable missing = null;
|
||||||
|
try { bad.payMissing("o-2"); } catch (Throwable e) { missing = e; }
|
||||||
|
t.line("fallback name does not exist -> " + missing.getClass().getName() + ": " + missing.getMessage());
|
||||||
|
assertThat(mismatched).isNotNull();
|
||||||
|
assertThat(missing).isNotNull();
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void printLibraryDefaults() {
|
||||||
|
Transcript t = Transcript.scratch("15-defaults.txt", "CircuitBreakerConfig.ofDefaults() in Resilience4j 2.4.0");
|
||||||
|
CircuitBreakerConfig c = CircuitBreakerConfig.ofDefaults();
|
||||||
|
t.line("slidingWindowType = " + c.getSlidingWindowType());
|
||||||
|
t.line("slidingWindowSize = " + c.getSlidingWindowSize());
|
||||||
|
t.line("minimumNumberOfCalls = " + c.getMinimumNumberOfCalls());
|
||||||
|
t.line("failureRateThreshold = " + c.getFailureRateThreshold());
|
||||||
|
t.line("slowCallRateThreshold = " + c.getSlowCallRateThreshold());
|
||||||
|
t.line("slowCallDurationThreshold = " + c.getSlowCallDurationThreshold());
|
||||||
|
t.line("waitIntervalFunctionInOpenState(1) = " + c.getWaitIntervalFunctionInOpenState().apply(1) + " ms");
|
||||||
|
t.line("permittedNumberOfCallsInHalfOpenState = " + c.getPermittedNumberOfCallsInHalfOpenState());
|
||||||
|
t.line("automaticTransitionFromOpenToHalfOpen = " + c.isAutomaticTransitionFromOpenToHalfOpenEnabled());
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
package com.ankurm.resilience.r4j;
|
||||||
|
|
||||||
|
import com.ankurm.resilience.Transcript;
|
||||||
|
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||||
|
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/** Output: 11-ignore-exceptions.txt, 12-rate-limiter.txt. */
|
||||||
|
@SpringBootTest
|
||||||
|
@DirtiesContext
|
||||||
|
class IgnoreExceptionsAndRateLimiterTest {
|
||||||
|
|
||||||
|
@Autowired R4jLookupService lookup;
|
||||||
|
@Autowired R4jRateLimiterService limiter;
|
||||||
|
@Autowired CircuitBreakerRegistry registry;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void businessExceptionsShouldNotTripTheBreaker() {
|
||||||
|
Transcript t = Transcript.scratch("11-ignore-exceptions.txt",
|
||||||
|
"Same exception, two breakers, one line of YAML apart");
|
||||||
|
CircuitBreaker counted = registry.circuitBreaker("lookupCounted");
|
||||||
|
CircuitBreaker ignored = registry.circuitBreaker("lookupIgnored");
|
||||||
|
for (int i = 1; i <= 4; i++) {
|
||||||
|
try { lookup.findCounted("p" + i); } catch (ProductNotFoundException ignoredEx) { }
|
||||||
|
try { lookup.findIgnored("p" + i); } catch (ProductNotFoundException ignoredEx) { }
|
||||||
|
}
|
||||||
|
t.line("lookupCounted after 4 'not found': state=" + counted.getState()
|
||||||
|
+ " failed=" + counted.getMetrics().getNumberOfFailedCalls());
|
||||||
|
t.line("lookupIgnored after 4 'not found': state=" + ignored.getState()
|
||||||
|
+ " failed=" + ignored.getMetrics().getNumberOfFailedCalls()
|
||||||
|
+ " buffered=" + ignored.getMetrics().getNumberOfBufferedCalls());
|
||||||
|
assertThat(counted.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||||
|
assertThat(ignored.getState()).isEqualTo(CircuitBreaker.State.CLOSED);
|
||||||
|
assertThat(ignored.getMetrics().getNumberOfBufferedCalls()).isZero();
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rateLimiterRejectsTheFourthCallInAOneSecondWindow() throws InterruptedException {
|
||||||
|
Transcript t = Transcript.scratch("12-rate-limiter.txt", "limitForPeriod=3, limitRefreshPeriod=1s");
|
||||||
|
for (int i = 1; i <= 4; i++) {
|
||||||
|
t.line("call " + i + " -> " + limiter.search("q" + i));
|
||||||
|
}
|
||||||
|
Thread.sleep(1100);
|
||||||
|
String after = limiter.search("q5");
|
||||||
|
t.line("after 1.1s -> " + after);
|
||||||
|
assertThat(after).startsWith("results:");
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
+75
@@ -0,0 +1,75 @@
|
|||||||
|
package com.ankurm.resilience.r4j;
|
||||||
|
|
||||||
|
import com.ankurm.resilience.Transcript;
|
||||||
|
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||||
|
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Slow is a failure mode too. Output: 08-slow-call-rate.txt, 09-timelimiter.txt,
|
||||||
|
* 10-timelimiter-plus-breaker.txt.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
@DirtiesContext
|
||||||
|
class LatencyAndTimeoutTest {
|
||||||
|
|
||||||
|
@Autowired R4jSlowCallService slow;
|
||||||
|
@Autowired R4jTimeLimiterService timeLimited;
|
||||||
|
@Autowired CircuitBreakerRegistry registry;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void breakerOpensOnLatencyAloneWithZeroFailures() throws Exception {
|
||||||
|
Transcript t = Transcript.scratch("08-slow-call-rate.txt",
|
||||||
|
"slowCallDurationThreshold=200ms, slowCallRateThreshold=50: opens with zero failures");
|
||||||
|
CircuitBreaker cb = registry.circuitBreaker("slowBreaker");
|
||||||
|
long[] sleeps = {10, 400, 10, 400};
|
||||||
|
for (int i = 0; i < sleeps.length; i++) {
|
||||||
|
String r = slow.call("c" + (i + 1), sleeps[i]);
|
||||||
|
t.line("call " + (i + 1) + " (" + sleeps[i] + "ms) -> " + r + " [state=" + cb.getState() + "]");
|
||||||
|
}
|
||||||
|
var m = cb.getMetrics();
|
||||||
|
t.line("failureRate=" + m.getFailureRate() + "% slowCallRate=" + m.getSlowCallRate()
|
||||||
|
+ "% numberOfFailedCalls=" + m.getNumberOfFailedCalls()
|
||||||
|
+ " numberOfSlowCalls=" + m.getNumberOfSlowCalls());
|
||||||
|
t.line("call 5 -> " + slow.call("c5", 10));
|
||||||
|
assertThat(m.getNumberOfFailedCalls()).isZero();
|
||||||
|
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void timeLimiterAnswersSlowCallsWithTheFallback() throws Exception {
|
||||||
|
Transcript t = Transcript.scratch("09-timelimiter.txt", "@TimeLimiter timeoutDuration=500ms");
|
||||||
|
long s1 = System.nanoTime();
|
||||||
|
String fast = timeLimited.lookup("a", 100).get();
|
||||||
|
t.line("100ms call -> " + fast + " (" + (System.nanoTime() - s1) / 1_000_000 / 100 * 100 + "ms bucket)");
|
||||||
|
long s2 = System.nanoTime();
|
||||||
|
String late = timeLimited.lookup("b", 2000).get();
|
||||||
|
long ms = (System.nanoTime() - s2) / 1_000_000;
|
||||||
|
t.line("2000ms call -> " + late + " (caller waited about 500ms, not 2000ms: " + (ms < 1000) + ")");
|
||||||
|
assertThat(fast).isEqualTo("found:a");
|
||||||
|
assertThat(late).isEqualTo("TIMED_OUT:b");
|
||||||
|
assertThat(ms).isBetween(450L, 1000L);
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void timeoutsCountAsFailuresAndEventuallyOpenTheBreaker() throws Exception {
|
||||||
|
Transcript t = Transcript.scratch("10-timelimiter-plus-breaker.txt",
|
||||||
|
"@CircuitBreaker + @TimeLimiter: timeouts are recorded as failures");
|
||||||
|
CircuitBreaker cb = registry.circuitBreaker("timeoutBreaker");
|
||||||
|
for (int i = 1; i <= 5; i++) {
|
||||||
|
long s = System.nanoTime();
|
||||||
|
String r = timeLimited.guardedLookup("k" + i, 2000).get();
|
||||||
|
t.line("call " + i + " -> " + r + " [state=" + cb.getState() + ", took "
|
||||||
|
+ ((System.nanoTime() - s) / 1_000_000 < 100 ? "<100ms" : "~500ms") + "]");
|
||||||
|
}
|
||||||
|
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
+95
@@ -0,0 +1,95 @@
|
|||||||
|
package com.ankurm.resilience.r4j;
|
||||||
|
|
||||||
|
import com.ankurm.resilience.FlakyDownstream;
|
||||||
|
import com.ankurm.resilience.Transcript;
|
||||||
|
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
|
||||||
|
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every state transition the post draws, observed through the breaker's own event stream
|
||||||
|
* instead of guessed from return values. Output (under target/transcripts): 06-state-transitions.txt, 07-fast-state-tests.txt.
|
||||||
|
*/
|
||||||
|
@SpringBootTest
|
||||||
|
@DirtiesContext
|
||||||
|
class StateTransitionsTest {
|
||||||
|
|
||||||
|
@Autowired R4jPaymentService service;
|
||||||
|
@Autowired FlakyDownstream downstream;
|
||||||
|
@Autowired CircuitBreakerRegistry registry;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void halfOpenFailureSendsTheBreakerStraightBackToOpen() throws InterruptedException {
|
||||||
|
Transcript t = Transcript.scratch("06-state-transitions.txt",
|
||||||
|
"State transitions seen through the event publisher (downstream stays dead)");
|
||||||
|
CircuitBreaker cb = registry.circuitBreaker("paymentService");
|
||||||
|
cb.reset();
|
||||||
|
List<String> transitions = new ArrayList<>();
|
||||||
|
cb.getEventPublisher().onStateTransition(e ->
|
||||||
|
transitions.add(e.getStateTransition().getFromState() + " -> " + e.getStateTransition().getToState()));
|
||||||
|
downstream.configure(Integer.MAX_VALUE);
|
||||||
|
|
||||||
|
for (int i = 1; i <= 5; i++) service.pay("order-" + i);
|
||||||
|
t.line("after 5 failing calls: state=" + cb.getState());
|
||||||
|
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||||
|
|
||||||
|
int callsBefore = downstream.callsSoFar();
|
||||||
|
Thread.sleep(2200); // waitDurationInOpenState=2s, automatic transition enabled
|
||||||
|
t.line("after waiting 2.2s (no call): state=" + cb.getState());
|
||||||
|
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.HALF_OPEN);
|
||||||
|
|
||||||
|
service.pay("probe-1");
|
||||||
|
service.pay("probe-2");
|
||||||
|
t.line("after 2 failing half-open probes: state=" + cb.getState()
|
||||||
|
+ " (downstream calls during probing: " + (downstream.callsSoFar() - callsBefore) + ")");
|
||||||
|
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
|
||||||
|
|
||||||
|
t.blank();
|
||||||
|
t.line("transitions recorded, in order:");
|
||||||
|
transitions.forEach(s -> t.line(" " + s));
|
||||||
|
assertThat(transitions).containsExactly(
|
||||||
|
"CLOSED -> OPEN", "OPEN -> HALF_OPEN", "HALF_OPEN -> OPEN");
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void youCanTestFallbackWithoutSleepingByForcingTheState() {
|
||||||
|
Transcript t = Transcript.scratch("07-fast-state-tests.txt",
|
||||||
|
"Testing without sleeping: force the state, assert the behaviour");
|
||||||
|
CircuitBreaker cb = registry.circuitBreaker("paymentService");
|
||||||
|
cb.reset();
|
||||||
|
downstream.configure(0); // healthy downstream
|
||||||
|
long start = System.nanoTime();
|
||||||
|
|
||||||
|
cb.transitionToOpenState();
|
||||||
|
String whileOpen = service.pay("order-x");
|
||||||
|
t.line("OPEN -> " + whileOpen);
|
||||||
|
assertThat(whileOpen).startsWith("FALLBACK").contains("CallNotPermittedException");
|
||||||
|
assertThat(downstream.callsSoFar()).isZero();
|
||||||
|
|
||||||
|
cb.transitionToHalfOpenState();
|
||||||
|
String probe = service.pay("order-y");
|
||||||
|
t.line("HALF_OPEN -> " + probe);
|
||||||
|
assertThat(probe).startsWith("OK");
|
||||||
|
|
||||||
|
cb.transitionToClosedState();
|
||||||
|
t.line("CLOSED -> " + service.pay("order-z"));
|
||||||
|
|
||||||
|
cb.transitionToForcedOpenState();
|
||||||
|
t.line("FORCED_OPEN -> " + service.pay("order-w"));
|
||||||
|
cb.transitionToClosedState();
|
||||||
|
|
||||||
|
long ms = (System.nanoTime() - start) / 1_000_000;
|
||||||
|
t.line("elapsed under 1s, no Thread.sleep: " + (ms < 1000));
|
||||||
|
assertThat(ms).isLessThan(1000);
|
||||||
|
t.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user