如何解决无法理解弹簧重试
我正在努力理解@Retryable。我需要的是在出现 5xx 异常时重试 3 次,如果重试也失败,则在恢复方法中抛出自定义异常。如果抛出其他异常,则捕获它并抛出自定义异常。
@Retryable(value = HttpServerErrorException.class,maxAttempts = 3,backoff = @Backoff(delay = 3000))
public String callToService(String key) {
String response;
try {
response = //assume a service call here
}catch (Exception ex) {
throw new customException("some message");
}
return response;
}
@Recover
public void retryFailed(HttpServerErrorException httpServerErrorException) {
throw new customException("some message");
}
解决方法
就您所添加的情况而言:
@Retryable(value = HttpServerErrorException.class,maxAttempts = 3,backoff = @Backoff(delay = 3000))
@Retryable
用于:
-
value = HttpServerErrorException.class
,因此您的方法将仅在HttpServerErrorException
从您的方法代码中出现/抛出时才会被重试,并且注意:如果有的话其他抛出的异常不会重试,也不会调用recover方法,因为recover方法只会在@Retryable中value中提到的异常时调用。 -
maxAttempts = 3
,因此它最多会重试执行您的方法 3 次 -
backoff = @Backoff(delay = 3000)
,因此在重试之间会保持 3000 毫秒的延迟。 - 重试 3 次后,如果您的方法仍然无效,您的
@Recover
方法将被HttpServerErrorException
调用
我希望它有意义并帮助您理解@Retryable
现在要实现你想要的,你需要实现它,如下所示:
@Retryable(value = HttpServerErrorException.class,backoff = @Backoff(delay = 3000))
public String callToService(String key) {
String response;
try {
response = //assume a service call here
} catch (HttpServerErrorException httpServerErrorException) {
throw httpServerErrorException;
} catch (Exception ex) {
throw new CustomException("some message");
}
return response;
}
@Recover
public void retryFailed(HttpServerErrorException httpServerErrorException) {
//do whatever you want here,when HttpServerErrorException occured more than 3 times
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。