设置超时时间为3秒,大部分能控制住,但是还是有10秒或者10分钟以上的
麻烦大神帮忙看看,以下是使用的方法,
private static Logger logger = LoggerFactory.getLogger(SpringRestTemplateUtils.class);
public static RestTemplate restTemplate;
public static CloseableHttpClient client;
public static HttpComponentsClientHttpRequestFactory factory;
static{
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
connMgr.setMaxTotal(2000);
connMgr.setDefaultMaxPerRoute(500);
client = HttpClients.custom()
.setConnectionManager(connMgr)
.build();
factory = new HttpComponentsClientHttpRequestFactory(client);
Thread thread = new Thread(new IdleConnectionMonitorThread(connMgr));
thread.start();
}
/**
*
* @param url 请求url
* @param httpMethod 请求方式:HttpMethod.POST HttpMethod.GET
* @param header 报文头设置
* @param params JSON格式
* @param readTimeOut 响应超时时间(单位:毫秒)
* @param connectTimeOut 请求超时时间(单位:毫秒)
* @return
*/
public static String exchange(String url, HttpMethod httpMethod, HttpHeaders header, JSONObject params, int readTimeOut, int connectTimeOut){
factory.setReadTimeout(readTimeOut);
factory.setConnectTimeout(connectTimeOut);
if(restTemplate == null){
restTemplate = new RestTemplate(factory);
}
//MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8");
//header.setContentType(type);
HttpEntity<JSONObject> h = new HttpEntity<>(params, header);
try {
ResponseEntity<String> resp = restTemplate.exchange(url, httpMethod, h, String.class);
return resp.getBody();
}catch (HttpClientErrorException e) {
return e.getResponseBodyAsString();
} catch (HttpServerErrorException e) {
return e.getResponseBodyAsString();
} catch (Exception e) {
logger.error("#########远程请求原始异常",e);
if(e.getCause() == null || (!(e.getCause() instanceof SocketTimeoutException) && !(e.getCause() instanceof ConnectTimeoutException))){
restTemplate = null;
}else{
throw e;
}
return null;
}
}