1

我想在我们的 Spring Boot 2.2.1.RELEASE 项目中使用弹性 4j-spring-boot2来重试针对第三方服务的失败请求。但是,由于某种原因,我无法注册 fallbackMethod:

pom.xml(相关依赖):

<!-- Resilience4J and dependencies -->
<dependency>
    <groupId>io.github.resilience4j</groupId>
    <artifactId>resilience4j-spring-boot2</artifactId>
    <version>1.2.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

应用程序.yaml:

resilience4j.retry:
  instances:
    exponentialBackoffBehaviour:
      maxRetryAttempts: 6
      waitDuration: 1s
      enableExponentialBackoff: true
      exponentialBackoffMultiplier: 2

我的Java代码:

@Retry(name = "exponentialBackoffBehaviour", fallbackMethod = "retryfallback")
private List<Applicant> requestApplicantList(HttpHeaders headers) throws JsonProcessingException {
    // This always returns 500 because is mocked
    ResponseEntity<String> response = restTemplate.exchange(URL, HttpMethod.GET, new HttpEntity(headers), String.class); 
    return objectMapper.readValue(response.getBody(), new TypeReference<List<Applicant>>() {});
}

private List<Applicant> retryfallback(HttpHeaders headers, Throwable e) {
    System.out.println("retryfallback");
    return new ArrayList<>();
}

“retryfallback”永远不会在控制台中打印。

我究竟做错了什么?

4

1 回答 1

1

注释仅适用于非私有的公共方法。

由于 Spring 的 AOP 框架基于代理的特性,私有方法根​​据定义不会被拦截。对于 JDK 代理,只能拦截代理上的公共接口方法调用。使用 CGLIB,代理上的公共和受保护的方法调用被拦截(如果需要,甚至包可见的方法)。但是,通过代理的常见交互应始终通过公共签名进行设计。

于 2020-01-10T13:01:17.940 回答