我有一个场景,我想记录每次重试尝试,当最后一次尝试失败(即maxAttempts
达到)时,抛出异常,假设创建了一个数据库条目。
我尝试使用带有 Spring Boot 的 Resilience4j-retry 来实现这一点,因此我使用application.yml
和注释。
@Retry(name = "default", fallbackMethod="fallback")
@CircuitBreaker(name = "default", fallbackMethod="fallback")
public ResponseEntity<List<Person>> person() {
return restTemplate.exchange(...); // let's say this always throws 500
}
回退将异常原因记录到应用程序日志中。
public ResponseEntity<?> fallback(Exception e) {
var status = HttpStatus.INTERNAL_SERVER_ERROR;
var cause = "Something unknown";
if (e instanceof ResourceAccessException) {
var resourceAccessException = (ResourceAccessException) e;
if (e.getCause() instanceof ConnectTimeoutException) {
cause = "Connection timeout";
}
if (e.getCause() instanceof SocketTimeoutException) {
cause = "Read timeout";
}
} else if (e instanceof HttpServerErrorException) {
var httpServerErrorException = (HttpServerErrorException) e;
cause = "Server error";
} else if (e instanceof HttpClientErrorException) {
var httpClientErrorException = (HttpClientErrorException) e;
cause = "Client error";
} else if (e instanceof CallNotPermittedException) {
var callNotPermittedException = (CallNotPermittedException) e;
cause = "Open circuit breaker";
}
var message = String.format("%s caused fallback, caught exception %s",
cause, e.getMessage());
log.error(message); // application log entry
throw new MyRestException (message, e);
}
当我调用此方法person()
时,重试会按照maxAttempt
配置进行。我希望我的自定义运行时MyRestException
在每次重试时被捕获并在最后一次(maxAttempt
达到时)抛出,所以我将调用包装在 try-catch 中。
public List<Person> person() {
try {
return myRestService.person().getBody();
} catch (MyRestException ex) {
log.error("Here I am ready to log the issue into the database");
throw new ex;
}
}
try-catch
不幸的是,当回退遇到并重新抛出立即被 my而不是 Resilience4j-retry 机制捕获的异常时,重试似乎被忽略了。
如何实现maxAttempts
被击中时的行为?有没有办法为这种情况定义一个特定的后备方法?