HTTP1.1长连接 NoHttpResponseException问题

大脑系统偶尔NoHttpResponseException错误,

httpclient-4.4.1.jar

初步诊断为是对方服务器关闭了http连接,而己方仍在用这个连接请求数据

http1.1默认是长连接的,多个请求可以在一个连接中传输,但对方服务器会关闭空闲的连接。

需要进一步确认,http连接策略,和tcp连接。

要主动关闭默认http1.1d长连接导致的过期连接和限制链接

新增连接长连接超时策略,ConnectionKeepAliveStrategy 

和开启

.evictExpiredConnections()//设置这两项,会开启定时任务清理过期和闲置的连接
.evictIdleConnections(IDLE_TIME, TimeUnit.MILLISECONDS)

同时新增失败重发策略,对于NoHttpResponseException异常进行重发。

        CLIENT = HttpClients.custom()
                    .setConnectionTimeToLive(ALIVE_TIME, TimeUnit.MILLISECONDS)
                    .setKeepAliveStrategy(keepAliveStrategy)
                    .setConnectionManager(connecManager)
                    .setRetryHandler(retryHandler)
                    .evictExpiredConnections()//设置这两项,会开启定时任务清理过期和闲置的连接
                    .evictIdleConnections(IDLE_TIME, TimeUnit.MILLISECONDS)
                    .build();
     //持久连接策略设置10秒。客户端的keepAlive无效
            ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
                @Override
                public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                    return ALIVE_TIME;
                }
            };


            //失败重发策略
            HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {
                @Override
                public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
                    if (i > 3) {
                        return false;
                    }
                    if (e instanceof NoHttpResponseException) {
                        //服务器没有响应,是服务器断开了连接应该重试
                        logger.error("NoHttpResponseExceptioni:" + i);
                        return true;
                    }

                    HttpClientContext clientContext = HttpClientContext.adapt(httpContext);
                    HttpRequest request = clientContext.getRequest();
                    boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                    //Retry if the request is considered idempotent
                    //如果请求类型不是HttpEntityEnclosingRequest,被认为是幂等的,那么就重试
                    //HttpEntityEnclosingRequest指的是有请求体的request,比HttpRequest多一个Entity属性
                    //而常用的GET请求是没有请求体的,POST、PUT都是有请求体的
                    //Rest一般用GET请求获取数据,故幂等,POST用于新增数据,故不幂等
                    if (idempotent) {
                        return true;
                    }
                    return false;
                }
            };

 

你可能感兴趣的:(HTTP1.1长连接 NoHttpResponseException问题)