如果我使用BasicHttpClientConnectionManager并执行对相同URL的请求,是否会重用Connection?

时间:2018-09-28 12:31:22

标签: httpclient apache-httpclient-4.x apache-commons-httpclient apache-httpcomponents

String URL_A ="http://www.google.com/";
BasicHttpClientConnectionManager connManager =new BasicHttpClientConnectionManager();
HttpClientBuilder httpBuilder = HttpClients.custom();
httpBuilder.setConnectionManager(connManager);
HttpClient httpClient = httpBuilder.build();
//First Execution
HttpGet httpGet = new HttpGet(URL_A);
HttpResponse httpResponse = httpClient.execute(httpGet);
EntityUtils.consume(httpResponse.getEntity());

//Second Execution
HttpGet httpGet2 = new HttpGet(URL_A);
HttpResponse httpResponse2 = httpClient.execute(httpGet2);
EntityUtils.consume(httpResponse2.getEntity());

//二次执行重用//第一次执行中建立了连接吗?

1 个答案:

答案 0 :(得分:1)

对于相同的URL,事实证明它重复使用了Connection。根据从BasicHttpClientConnectionManager提取的代码

中指定的
synchronized HttpClientConnection getConnection(final HttpRoute route, final Object state) {
        Asserts.check(!this.isShutdown.get(), "Connection manager has been shut down");
        if (this.log.isDebugEnabled()) {
            this.log.debug("Get connection for route " + route);
        }
        Asserts.check(!this.leased, "Connection is still allocated");
  

if(!LangUtils.equals(this.route,route)||   !LangUtils.equals(this.state,state)){                   closeConnection();               }

        this.route = route;
        this.state = state;
        checkExpiry();
        if (this.conn == null) {
            this.conn = this.connFactory.create(route, this.connConfig);
        }
        this.conn.setSocketTimeout(this.socketConfig.getSoTimeout());
        this.leased = true;
        return this.conn;
    }
相关问题