Apache HttpClient 5.x迁移:如何替换setRetryHandler为setRetryStrategy?
Apache HttpComponents Client 5.x 重试策略迁移方案
原代码逻辑回顾
旧版本通过DefaultHttpRequestRetryHandler配置了两个核心规则:
- 最大重试次数为
X requestSentRetryEnabled=true:允许重试已发送完成的请求(比如POST这类可能在服务器端产生副作用的请求)
5.x版本迁移步骤
在5.x中,RetryHandler被RetryStrategy替代,DefaultHttpRequestStrategy不再直接提供requestSentRetryEnabled参数,需通过HttpRequestRetryStrategies构建器实现相同逻辑:
HttpClientBuilder cb = HttpClients.custom(); // 构建自定义重试策略 RetryStrategy retryStrategy = HttpRequestRetryStrategies.custom() .maxRetries(X) // 设置最大重试次数,对应旧代码的X .retryOnSentRequests(true) // 开启已发送请求的重试,对应旧代码的requestSentRetryEnabled=true .build(); cb.setRetryStrategy(retryStrategy);
关键说明
- 5.x的
DefaultHttpRequestStrategy默认不重试已发送的请求,这是出于避免重复执行副作用请求的安全考虑;如果需要保留旧代码的重试逻辑,必须显式调用retryOnSentRequests(true)。 - 若只需默认重试规则+指定重试次数,可简化为
HttpRequestRetryStrategies.defaultStrategy(X),但此方式不包含已发送请求的重试。 - 如需更精细化控制(比如指定哪些异常/状态码才重试),可在
custom()构建器后追加配置,例如:HttpRequestRetryStrategies.custom() .maxRetries(X) .retryOnSentRequests(true) .retryOnException(e -> e instanceof IOException) // 仅重试IO异常 .retryOnStatusCodes(500, 502, 503) // 仅重试指定状态码 .build();
内容的提问来源于stack exchange,提问作者Lucifer
相关产品推荐
相关产品推荐

