resilience4j Spring 启动 2

resilience4j Spring Boot 2

尝试一个简单的 Spring Boot 2 + Resilience4j 项目。

但面临一个问题,即尽管主机应用程序已关闭,断路器始终处于关闭状态

服务class

@Autowired
private RestTemplate restTemplate;

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

@CircuitBreaker(name = "mainService", fallbackMethod="testFallBack")
public ResponseEntity<String> invokeService(int i) {
    return restTemplate.exchange(
            "http://localhost:9092/", // This service is always down
            HttpMethod.GET,
            null,
            String.class
    );
}

private  ResponseEntity<String> testFallBack(int i, Exception e) {
    return new ResponseEntity<String>("In fallback method", HttpStatus.INTERNAL_SERVER_ERROR);
}

Resilience4J 配置

management.endpoint.health.show-details: always
management.health.circuitbreakers.enabled: true

resilience4j:
  circuitbreaker:
    configs:
      default:
        registerHealthIndicator: true
        minimumNumberOfCalls: 5
        permittedNumberOfCallsInHalfOpenState: 3
        automaticTransitionFromOpenToHalfOpenEnabled: true
        waitDurationInOpenState: 5s
        failureRateThreshold: 50
        eventConsumerBufferSize: 10
    instances:
      mainService:
        baseConfig: default

控制器多次调用该服务,我希望它在至少 5 次调用后 回退,但 断路器始终处于关闭状态 并且对于来自控制器的每次调用,都会调用主机服务并拒绝连接。

依赖项:spring-boot-starter-web,resilience4j-spring-boot2,spring-aop,spring-boot-启动器执行器

早些时候,我尝试了使用 CircuitBreakerRegistry 和 Decorator 函数的编程方法,效果如预期。

其实你对断路器参数的理解有误。见 documentation:

minimumNumberOfCalls, default: 100

Configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate or slow call rate.

For example, if minimumNumberOfCalls is 10, then at least 10 calls must be recorded, before the failure rate can be calculated. If only 9 calls have been recorded the CircuitBreaker will not transition to open even if all 9 calls have failed.

slidingWindowSize, default: 100

Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed.

在你的配置中,有

minimumNumberOfCalls: 5
slidingWindowSize: 100  ## implicitly, because you have not set this parameters

还有你

expect it to fallback after minimum 5 calls

但是,您的断路器在 100 次故障后打开,而不是在 5 次后打开。