原创转载请注明出处: https://www.cnblogs.com/agilestyle/p/15166657.html
Maven Dependency
... <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-boot2</artifactId> <version>1.7.1</version> </dependency> ...
CircuitBreaker
https://resilience4j.readme.io/docs/circuitbreaker
# Resilience4j CircuitBreaker config resilience4j.circuitbreaker.configs.default.sliding-window-size=100 resilience4j.circuitbreaker.configs.default.permitted-number-of-calls-in-half-open-state=10 resilience4j.circuitbreaker.configs.default.wait-duration-in-open-state=10000 resilience4j.circuitbreaker.configs.default.failure-rate-threshold=60 resilience4j.circuitbreaker.configs.default.event-consumer-buffer-size=10 resilience4j.circuitbreaker.configs.default.register-health-indicator=true resilience4j.circuitbreaker.instances.xxx-web-client.base-config=default
Retry
https://resilience4j.readme.io/docs/retry
# Resilience4j Retry config resilience4j.retry.instances.xxxSvc.max-retry-attempts=3 resilience4j.retry.instances.xxxSvc.wait-duration=800ms resilience4j.retry.instances.xxxSvc.retry-exceptions=org.fool.exception.ApplicationException
Note:设置抛出 ApplicationException 时才会触发 retry
Test
Trigger CircuitBreaker
@RequestMapping("/test/{userId}") @CircuitBreaker(name = "xxx-web-client", fallbackMethod = "fallbackTest") @Retry(name = "xxxSvc", fallbackMethod = "fallbackTest") public String test(@PathVariable String userId) { String result = null; System.out.println("mock business logic with userId: " + userId); int i = 1 / 0; return result; } private String fallbackTest(String userId, RuntimeException e) { System.err.println("fallbackTest invoked with userId: " + userId + ", exception:" + e); return null; }
Console Output
mock business logic with userId: 1 fallbackTest invoked with userId: 1, exception:java.lang.ArithmeticException: / by zero
Note: 没有 retry,直接进入熔断方法
Trigger Retry
@RequestMapping("/test/{userId}") @CircuitBreaker(name = "xxx-web-client", fallbackMethod = "fallbackTest") @Retry(name = "xxxSvc", fallbackMethod = "fallbackTest") public String test(@PathVariable String userId) throws ApplicationException { String result = null; System.out.println("mock business logic with userId: " + userId); try { int i = 1 / 0; } catch (Exception e) { throw new ApplicationException("exception happen"); } return result; } private String fallbackTest(String userId, RuntimeException e) { System.err.println("fallbackTest invoked with userId: " + userId + ", exception:" + e); return null; }
Console Output
mock business logic with userId: 1 mock business logic with userId: 1 mock business logic with userId: 1
Note: 这条 log 会输出 3 次,即 retry 了 3 次,并且没有进入熔断方法
Reference
https://resilience4j.readme.io/docs/getting-started-3
欢迎点赞关注和收藏