/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.spring.rest;

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;

/**
 * @author 田平 create 2022-06-10 16:20:07
 */
public class TimeoutHttpClientRequestFactory extends HttpComponentsClientHttpRequestFactory {
	/**
	 * 单位毫秒
	 */
	static ThreadLocal<Integer> socketTimeoutMs = new ThreadLocal<>();

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

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

		RequestConfig config = createRequestConfig(getHttpClient());

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

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

}
