RestTemplate(httpclient) 动态设置超时时间

动态设置RestTemplate(httpclient)的超时时间

httpclient版本


    org.apache.httpcomponents
    httpclient
    4.5.1

 RestTemplate构造

HttpClientBuilder httpClientBuilder = HttpClients.custom();
// HttpClient相关配置
HttpClient httpClient = httpClientBuilder.build();

// 使用自定义HttpClientRequestFactory
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpClientRequestFactory(httpClient);
clientHttpRequestFactory.setConnectTimeout(5000);
// 即为 SocketTimeout
clientHttpRequestFactory.setReadTimeout(30000);  
clientHttpRequestFactory.setConnectionRequestTimeout(5000);

RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory)

HttpClientRequestFactory类

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.protocol.HttpContext;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;

import java.net.URI;

public class HttpClientRequestFactory extends HttpComponentsClientHttpRequestFactory {

    public static ThreadLocal socketTimeoutThreadLocal = new ThreadLocal<>();

    public HttpClientRequestFactory(HttpClient httpClient) {
        super(httpClient);
    }

    @Override
    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
        HttpContext context = HttpClientContext.create();

        RequestConfig config = createRequestConfig(getHttpClient());

        // 从ThreadLocal中获取超时时间,并设置到context中
        Integer socketTimeout = socketTimeoutThreadLocal.get();
        if (null != socketTimeout) {
            RequestConfig.Builder builder = RequestConfig.copy(config);
            builder.setSocketTimeout(socketTimeout);
            config = builder.build();
        }

        context.setAttribute(HttpClientContext.REQUEST_CONFIG, config);
        return context;
    }
}

使用

// 设置当前请求超时时间
HttpClientRequestFactory.socketTimeoutThreadLocal.set(15000);
try {
    restTemplate.***()
} finally {
    // 清理ThreadLocal中超时时间
    HttpClientRequestFactory.socketTimeoutThreadLocal.remove();
}

原理

org.apache.http.impl.execchain.MainClientExec.execute(...)

httpclient在发起请求时会优先使用context中的超时时间设置

final RequestConfig config = context.getRequestConfig();
...
final int timeout = config.getSocketTimeout();
if (timeout >= 0) {
	managedConn.setSocketTimeout(timeout);
}

 

你可能感兴趣的:(Java)