首页 > 解决方案 > 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);
    }
}

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

标签: springspring-bootspring-retryresilience4j-retry

解决方案


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

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


推荐阅读