测试会因http客户端连接池问题

时间:2017-08-10 10:54:32

标签: java connection-pooling apache-httpclient-4.x

当我运行我的测试时,他们会挂在同一点:当我尝试发送请求时。 我知道池中没有免费连接,但我不知道如何解决这个问题。有任何想法吗? 代码:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
    public class ClientTest {
private static String username = ITProperties.getInstance().getProperty("username");
private static String password = ITProperties.getInstance().getProperty("password");
private static CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
private static UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);

public static final HttpClient HTTP_CLIENT = buildHttpClientWithCredentials();

public static HttpClient buildHttpClientWithCredentials() {
    credentialsProvider.setCredentials(AuthScope.ANY, credentials);
    return HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
}

    @Test
    public void testWhenClientNotFound() throws JSONException, IOException {
        String requestBody = new RequestBody().setSum(100000L).setDay(7).toString();
        HttpPost request = RequestProvider.getPostRequest(URL, requestBody);

        HttpResponse response = HTTP_CLIENT.execute(request); //HERE EXECUTION HANGS

        assertThat(response.getStatusLine().getStatusCode()).isEqualTo(404);
    }

    ...
    }

来自日志:

2017-08-10 12:24:13,787 DEBUG | main | org.apache.http.client.protocol.RequestAddCookies.process.123 | CookieSpec selected: default 
2017-08-10 12:24:13,787 DEBUG | main | org.apache.http.client.protocol.RequestAddCookies.process.168 | Cookie [version: 0][name: JSESSIONID][value: 00000000000000000000000000000][domain: localhost][path: /][expiry: null] match [localhost:9900/path/to/my/resource] 
2017-08-10 12:24:13,787 DEBUG | main | org.apache.http.client.protocol.RequestAuthCache.process.77 | Auth cache not set in the context 
2017-08-10 12:24:13,787 DEBUG | main | org.apache.http.impl.conn.PoolingHttpClientConnectionManager.requestConnection.255 | Connection request: [route: {}->http://localhost:9900][total kept alive: 0; route allocated: 2 of 2; total allocated: 2 of 20] 
2017-08-10 12:24:33,919 DEBUG | HikariPool-1 housekeeper | com.zaxxer.hikari.pool.HikariPool.logPoolState.378 | HikariPool-1 - Pool stats (total=2, active=0, idle=2, waiting=0) 

1 个答案:

答案 0 :(得分:1)

首先,你必须关闭你的回复:

CloseableHttpResponse response = httpclient.execute(httpget);
try {
    <...>
} finally {
    response.close();
}

然后您可以按照here所述配置线程池:

PoolingHttpClientConnectionManager cm = new 
PoolingHttpClientConnectionManager();
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
HttpHost localhost = new HttpHost("locahost", 80);
cm.setMaxPerRoute(new HttpRoute(localhost), 50);
CloseableHttpClient httpClient = HttpClients.custom()
    .setConnectionManager(cm)
    .build();