2017-08-10 214 views
0

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

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) 
+0

更新了代码。我正在检查响应代码。 – IKo

+0

它只是网址。像:http:// localhost:9900/path/to/my/resource – IKo

回答

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