Skip to content

Commit

Permalink
🎨 #2390 【公共问题】ApacheHttpClientBuilder增加支持配置重试策略和超时策略的参数
Browse files Browse the repository at this point in the history
  • Loading branch information
haoyanbing authored Nov 17, 2021
1 parent 8b4c105 commit 1f830ec
Showing 1 changed file with 22 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
Expand Down Expand Up @@ -92,7 +93,17 @@ public class DefaultApacheHttpClientBuilder implements ApacheHttpClientBuilder {
*/
private String userAgent;

private final HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
/**
* 自定义重试策略
*/
private HttpRequestRetryHandler httpRequestRetryHandler;

/**
* 自定义KeepAlive策略
*/
private ConnectionKeepAliveStrategy connectionKeepAliveStrategy;

private final HttpRequestRetryHandler defaultHttpRequestRetryHandler = new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
Expand Down Expand Up @@ -187,7 +198,16 @@ private synchronized void prepare() {
.setConnectTimeout(this.connectionTimeout)
.setConnectionRequestTimeout(this.connectionRequestTimeout)
.build()
).setRetryHandler(this.httpRequestRetryHandler);
);

// 设置重试策略,没有则使用默认
httpRequestRetryHandler = httpRequestRetryHandler == null ? defaultHttpRequestRetryHandler : httpRequestRetryHandler;
httpClientBuilder.setRetryHandler(httpRequestRetryHandler);

// 设置KeepAliveStrategy,没有使用默认
if (connectionKeepAliveStrategy != null) {
httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy);
}

if (StringUtils.isNotBlank(this.httpProxyHost) && StringUtils.isNotBlank(this.httpProxyUsername)) {
// 使用代理服务器 需要用户认证的代理服务器
Expand Down

0 comments on commit 1f830ec

Please sign in to comment.