如何在Resilience4j中配置retryOnResultPredicate?含HTTP状态判断需求
Resilience4j 重试配置示例(基于HTTP状态码断言)
完整配置
resilience4j.retry: configs: default: maxAttempts: 3 waitDuration: 100 failAfterMaxAttempts: true # 通过SpEL引用自定义的HTTP状态码断言Bean retryOnResultPredicate: "#{@httpStatusRetryPredicate}" retryExceptions: - org.springframework.web.client.HttpServerErrorException - java.util.concurrent.TimeoutException - java.io.IOException ignoreExceptions: - io.github.robwin.exception.BusinessException
自定义HTTP状态码断言实现
创建一个Spring管理的Predicate Bean,用于判断HTTP响应状态码是否需要重试:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import java.util.function.Predicate; @Component("httpStatusRetryPredicate") public class HttpStatusRetryPredicate implements Predicate<ResponseEntity<?>> { @Override public boolean test(ResponseEntity<?> response) { // 规则:遇到5xx服务器错误时触发重试,可根据业务调整 return response.getStatusCode().is5xxServerError(); // 如需包含特定4xx(如429限流),可修改为: // return response.getStatusCode().is5xxServerError() || response.getStatusCode() == HttpStatus.TOO_MANY_REQUESTS; } }
关键配置说明
failAfterMaxAttempts: true:达到maxAttempts(含首次调用)的重试次数后,直接抛出MaxRetriesExceededException,而非返回最后一次调用结果。retryOnResultPredicate:通过SpEL表达式绑定自定义断言Bean,实现基于HTTP响应状态码的重试触发逻辑。- 断言Bean的
test方法可灵活扩展,适配不同业务场景下的状态码重试规则。
内容的提问来源于stack exchange,提问作者Ajith Ahangama Vitharanalage
相关产品推荐
相关产品推荐

