Springboot中如何根据HTTP响应代码执行重试

问题描述

@Retryable(value = ABCDException.class,maxAttemptsExpression = 3,backoff = @Backoff(delayExpression = "#{${application.delay}}"))

public String postABCDrequest(ABCDrequest abcdRequest) throws ABCDException {
    try {
        return restCalltopostData(abcdRequest);
    } catch (AnyException e) {
        log.error("Error Occured ",e);
        throw new ABCDException("Error Occured ",e);
    }
}

在这方法中,只有在我收到某些响应代码时才需要重新尝试发布数据。我搜索了一些不适合我的解决方案的选项。使用注解有没有更简单的方法

解决方法

在 catch 块中,您将无法获得响应代码。由于您对所有 5xx 感兴趣,请检查 response.getStatusCode().is5xxServerError() 并重新抛出异常 ABCDException.class 如果异常在服务器端处理良好并返回状态代码。这样,您的代码将继续重试所有 5xx 异常,直到 maxAttempts 耗尽。

否则,您可以简单地通过替换 HttpServerErrorException.class 来重试 ABCDException.class