问题描述
我有一种情况,我想记录每次重试的尝试,当最后一次尝试失败(即达到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
而不是Resilience4j-retry机制捕获的异常,因此重试似乎被忽略了。
如何击中maxAttempts
时的行为?有没有办法为这种情况定义特定的后备方法?
解决方法
为什么不捕获异常并将其映射到Service方法中的MyRestException
,例如myRestService.person()
?
它使您的配置变得更加简单,因为您只需在RetryConfig和CircuitBreakerConfig的配置中添加MyRestException
。
如果您不想将样板代码添加到每个Service方法中,Spring RestTemplate还具有注册自定义ResponseErrorHandler的机制。 -> https://www.baeldung.com/spring-rest-template-error-handling
我不会将CallNotPermittedException
映射到MyRestException
。打开CircuitBreaker时,您不想重试。将CallNotPermittedException
添加到RetryConfig中被忽略的异常列表中。
我认为您根本不需要后备机制。我将一个异常映射到另一个异常不是“后备”。