java - @Retry FallbackMethod 未注册

标签 java spring-boot resilience4j

我想在 Spring Boot 2.2.1.RELEASE 项目中使用 resilience4j-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>

application.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”永远不会打印在控制台中。

我做错了什么?

最佳答案

注释仅适用于公共(public)方法,不适用于私有(private)方法。

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

关于java - @Retry FallbackMethod 未注册,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59323410/

相关文章:

java - 为什么我的 2D Array Maze 不打印生成的内容?

java - 在 spring boot 项目中使用 spring eclipse sts 逆向工程数据库表

java - Eclipse:升级到 Spring Boot 2.0.1 后无法检测类异常

java - Spring -MongoDB

java - Resilience4j Retry - 记录来自客户端的重试尝试?

java - Runnable 中具有 Thread 类型的局部字段

java.io.IOException : No X-Jenkins-CLI2-Port (jenkins cli not working ) 异常

c# - 无法弄清楚这些 C# 和 Java 代码的不同之处

java - UnitTesting Spring Boot 中 Unresolved 依赖关系

java - 使用 Spring Boot 的 Resilience4J 断路器的 Bean 配置