问题描述
我有一种情况,我想记录每次重试的尝试,当最后一次尝试失败(即达到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
时的行为?有没有办法为这种情况定义特定的后备方法?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)