我正在尝试实现重试逻辑。我的代码按预期工作,直到重试方法的返回类型无效。当我将其更改为字符串时,@Recover 停止工作。
@Component
public class AdapterImpl {
int count = 0;
@Retryable(include = {NullPointerException.class, IllegalStateException.class}, backoff = @Backoff(delay = 100, maxDelay = 101), maxAttempts = 5)
public void retry(String foo) {
System.out.println(foo + " " + count++);
if (foo.equals("foo")) {
throw new NullPointerException("foo");
} else if (foo.equals("bar")) {
throw new IllegalStateException("bar");
}
// return "hi";
}
@Recover
public void connectionException(NullPointerException e) {
System.out.println("Retry failure NullPointerException");
}
@Recover
public void connectionException(IllegalStateException e) {
System.out.println("Retry failure IllegalStateException");
}
}
对于 foo 和 bar,重试逻辑是有效的。日志如下
bar 0
bar 1
bar 2
bar 3
bar 4
Retry failure IllegalStateException
但是当我将重试方法的返回类型更改为字符串时,@Recover 方法停止工作。
@Retryable(include = {NullPointerException.class, IllegalStateException.class}, backoff = @Backoff(delay = 100, maxDelay = 101), maxAttempts = 5)
public String retry(String foo) {
System.out.println(foo + " " + count++);
if (foo.equals("foo")) {
throw new NullPointerException("foo");
} else if (foo.equals("bar")) {
throw new IllegalStateException("bar");
}
return "hi";
}
日志如下
bar 0
bar 1
bar 2
bar 3
bar 4
2020-04-26 23:28:30.800 ERROR 59644 --- [nio-8087-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.retry.ExhaustedRetryException: Cannot locate recovery method; nested exception is java.lang.IllegalStateException: bar] with root cause
java.lang.IllegalStateException: bar
我的 build.gradle 是
plugins {
id 'java'
id 'org.springframework.boot' version '2.2.6.RELEASE'
id 'io.spring.dependency-management' version '1.0.9.RELEASE'
}
group 'com.demo.web'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.retry:spring-retry'
compile 'org.springframework:spring-aspects'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testCompile group: 'junit', name: 'junit', version: '4.12'
}
我究竟做错了什么?