使用 httpclient.4.5.6
springboot 2.0.8RELEASE
RetryExec.java
CloseableHttpResponse execute()
try {
return this.requestExecutor.execute(route, request, context, execAware);
} catch(final IOException ex) {
if (retryHandler.retryRequest(ex.execCount, context) {
} else {
if (ex instanceof NoHttpResponseException) {
}
}
}
@Configuration
public class RestTemplateConfig {
// builder.build();的并发量是5,不如 new RestTemplate() 默认200
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
这样建的RestTemplate 没有重发 NoHttpResponseException和org.apache.http.conn.ConnectTimeoutException 需要自定义 RetryHandler
NoHttpResponseException 服务端断开连接,客户端使用了断开的连接发送,导致报错,默认的RestTemplate 会有connection有效性检查,默认2秒检查一次
要设置客户端的Keep-Alive,客户端应该设置的比服务端短,默认RestTemplate不会设置
带Keep-Alive的头部 示例
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
Date: Thu, 11 Aug 2016 15:23:13 GMT
Keep-Alive: timeout=5, max=1000
Last-Modified: Mon, 25 Jul 2016 04:32:39 GMT
Server: Apache
(body)
增加 Keep-Alive,设置可以减少NoHttpResponseException
String url = "http://***";
long startTime = System.currentTimeMillis();
//JSONObject json = restTemplate.getForObject("url", JSONObject.class);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Keep-Alive", "timeout=30, max=1000");
JSONObject json = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(null, httpHeaders), JSONObject.class).getBody();
来源:oschina
链接:https://my.oschina.net/u/4289228/blog/3334429