首页 > 编程语言 > 详细

spring RestTemplate 出现 NoHttpResponseException 和 ConnectionTimeoutException

时间:2019-12-05 20:52:36      阅读:479      评论:0      收藏:0      [点我收藏+]

使用 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();

 

spring RestTemplate 出现 NoHttpResponseException 和 ConnectionTimeoutException

原文:https://www.cnblogs.com/zhongchang/p/11991704.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!