Spring Boot Resilience4J注解未能打开电路

3

我查看了关于Resilience4J的问题,但是它们的答案并没有帮到我。我正在尝试在我的Spring Boot 2.x项目中实现来自Resilience4J的@CircuitBreaker注释。电路断路器围绕一个非常简单的函数实现。然而,当我提供错误的URL时,无论我发送多少次请求,电路都不会打开。我甚至将所有内容提取到独立应用程序中并运行了100次观察它无休止地失败。你们有什么建议吗?

    @CircuitBreaker(name = "backendA")
    @Component
    public class ResilientClient {

        private HttpClient httpClient;

        private static final Logger log = LoggerFactory.getLogger(ResilientClient.class);

        public ResilientClient() {

            httpClient = HttpClient.newBuilder().build();
        }


        @Bulkhead(name = "backendA")
        public String processPostRequest(String body, String[] headers, String url) {

            HttpResponse<String> response = null;

            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .headers(headers)
                .build();

            try {
                response =  httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            } catch (IOException e) {
                throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "This is a remote exception");
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.error("Interrupted Exception: " + e.getLocalizedMessage(), e);

            }
            return response != null ? response.body() : null;
    };

// None of these functions ever get invoked

    private String fallback(Throwable e){
        log.info("generic throwable caught");
        return "generic result";
    }

    private String fallback(String param1, String[] headers, String url, Throwable e) {
        log.info("Fallback method invoked for Throwable: " + param1);
        return null;
    }

    private String fallback(String param1, String[] headers, String url, ConnectException e) {
        log.info("Fallback method invoked for ConnectException: " + param1);
        return null;
    }

}



配置文件直接从Github示例中获取。
resilience4j.circuitbreaker:
  configs:
    default:
      registerHealthIndicator: false
      slidingWindowSize: 10
      minimumNumberOfCalls: 5
      permittedNumberOfCallsInHalfOpenState: 3
      automaticTransitionFromOpenToHalfOpenEnabled: true
      waitDurationInOpenState: 2s
      failureRateThreshold: 50
      eventConsumerBufferSize: 10
      recordExceptions:
        - org.springframework.web.client.HttpServerErrorException
        - java.io.IOException
      ignoreExceptions:
        - io.github.robwin.exception.BusinessException
    shared:
      registerHealthIndicator: true
      slidingWindowSize: 100
      permittedNumberOfCallsInHalfOpenState: 30
      waitDurationInOpenState: 1s
      failureRateThreshold: 50
      eventConsumerBufferSize: 10
      ignoreExceptions:
        - io.github.robwin.exception.BusinessException
  instances:
    backendA:
      baseConfig: default
    backendB:
      registerHealthIndicator: true
      slidingWindowSize: 10
      minimumNumberOfCalls: 10
      permittedNumberOfCallsInHalfOpenState: 3
      waitDurationInOpenState: 1s
      failureRateThreshold: 50
      eventConsumerBufferSize: 10
      recordFailurePredicate: io.github.robwin.exception.RecordFailurePredicate
resilience4j.retry:
  configs:
    default:
      maxRetryAttempts: 2
      waitDuration: 100
      retryExceptions:
        - org.springframework.web.client.HttpServerErrorException
        - java.io.IOException
      ignoreExceptions:
        - io.github.robwin.exception.BusinessException
  instances:
    backendA:
      maxRetryAttempts: 3
    backendB:
      maxRetryAttempts: 3
resilience4j.bulkhead:
  configs:
    default:
      maxConcurrentCalls: 100
  instances:
    backendA:
      maxConcurrentCalls: 10
    backendB:
      maxWaitDuration: 10ms
      maxConcurrentCalls: 20

resilience4j.thread-pool-bulkhead:
  configs:
    default:
      maxThreadPoolSize: 4
      coreThreadPoolSize: 2
      queueCapacity: 2
  instances:
    backendA:
      baseConfig: default
    backendB:
      maxThreadPoolSize: 1
      coreThreadPoolSize: 1
      queueCapacity: 1

resilience4j.ratelimiter:
  configs:
    default:
      registerHealthIndicator: false
      limitForPeriod: 10
      limitRefreshPeriod: 1s
      timeoutDuration: 0
      eventConsumerBufferSize: 100
  instances:
    backendA:
      baseConfig: default
    backendB:
      limitForPeriod: 6
      limitRefreshPeriod: 500ms
      timeoutDuration: 3s

尝试测试它的代码

SpringBootApplication
public class CircuitsApplication {

    private static final Logger logger = LoggerFactory.getLogger(CircuitsApplication.class);

    static ResilientClient resilientClient = new ResilientClient();

    public static void main(String[] args) {
        //SpringApplication.run(CircuitsApplication.class, args);
        for (int i = 0; i < 100; i++){
            try {
                String body = "body content";
                String[] headers = new String[]{"header", "value"};
                String url = "http://a.bad.url";
                String result = resilientClient.processPostRequest(body, headers, url);
                logger.info(result);
            } catch (Exception ex){
                logger.info("Error caught in main loop");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}


我已经尝试为方法本身添加Circuitbreaker注释。我尝试创建供应商并进行装饰。我尝试添加Bulkhead,删除Bulkhead。我尝试添加具有不同签名的附加回退方法。我尝试添加和不添加@Component。
我的日志中最终只显示了这个100次:
14:33:10.348 [main] INFO c.t.circuits.CircuitsApplication - Error caught in main loop

我不确定我缺少什么。非常感谢您的帮助。


你能解决这个问题吗? - Rocky4Ever
1个回答

3
我认为这样做不会奏效。首先,你实例化了ResilientClient作为new ResilientClient()。你必须使用已创建的Bean而不是自己实例化它。@CircuitBreaker注解使用了spring-aop。所以你需要将你的类运行为SpringBootApplicaiton。
其次,你只记录HttpServerErrorExceptionIOException作为故障。因此断路器将所有其他异常(除上述异常及其子类之外)视为成功。

为了明确,上面的代码是我从我的Spring Boot应用程序中提取的。 :) 现在,客户端是在构造函数中使用(@Autowired ResilientClient resilientClient)从服务层实例化的。在Spring Boot 2中使用Resilience4J有几个需要注意的地方没有在文档中涵盖,包括需要让Spring自动装配bean或设置一个配置类,以及文档中的示例Java代码有一个未定义的变量。 - Jeremy Smith
1
如果您想在所有异常上重试,请尝试将 java.lang.Throwable 添加到 resilience4j.circuitbreaker.configs.default.recordExceptions。您可以将忽略的异常添加到 resilience4j.circuitbreaker.configs.default.ignoreExceptions 中。 - Akhil Bojedla
2
默认情况下,所有异常都被视为失败。您不必将Throwable添加到recordExceptions中。您只需要将异常添加到ignoreExpections列表中即可。 - Robert Winkler
如果您不配置recordExceptions,它们会记录所有异常。但是,如果您在recordExceptions配置中放置了一组异常列表,则它们不会被记录。recordExceptions:将作为失败记录并因此增加失败率的异常列表。 与列表中的任何异常匹配或继承的异常都计为失败,除非通过ignoreExceptions明确忽略。 如果您指定了异常列表,则除非通过ignoreExceptions明确忽略,否则所有其他异常都计为成功。 - Akhil Bojedla
2
我知道。我写的。 :) 如果您不指定应记录的异常列表,则除非明确忽略,否则将记录所有异常。 - Robert Winkler
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接