zoukankan      html  css  js  c++  java
  • spring RestTemplate 出现 NoHttpResponseException 和 ConnectionTimeoutException

    使用 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();
  • 相关阅读:
    log4j的使用
    关于spring读取配置文件的两种方式
    BeanUtils组件的使用
    javaee 自定义标签实战
    javaweb中的标签的核心标签库的常用标签
    对接口的思考
    二分查找
    java抽象类
    多例集合
    js中for循环的研究
  • 原文地址:https://www.cnblogs.com/zhongchang/p/11991704.html
Copyright © 2011-2022 走看看