try{
// create new httpPost request with url of his class
HttpPost httpPost = new HttpPost( "http://192.168.1.229:8080/flightcache/flightcache" );
// create params and add it to httpPost
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add( new BasicNameValuePair( "json_req", format ) );
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( paramList );
httpPost.setEntity( formEntity );
// execute request and save response
CloseableHttpResponse response = httpclient.execute( httpPost, context );
HttpEntity entity = response.getEntity();
for( Header header : response.getAllHeaders() ){
System.out.println( header.getName() + ":" + header.getValue() );
}
resp = entity.getContent().available() > 0;
response.close();
httpclient.close();
// return the response
}
catch( Exception e ){
e.printStackTrace();
}
Я пытаюсь отправить несколько запросов HttpPost одновременно с моим сервлетом, но только один поток, выполняющий указанный выше код, получает ответ. Я проверил свой сервлет, но ответы написаны правильно. httpClient
был создан следующим образом.
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
Кто-нибудь может помочь/объяснить мне, почему только один поток получает ответ?
Заранее спасибо
public static void main( String[] args ) throws Exception{
FileUtil.init();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal( 200 );
cm.setDefaultMaxPerRoute( 200 );
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager( cm ).build();
HTTPThread.THREAD_COUNT = 2;
HTTPThread.start = new CountDownLatch( HTTPThread.THREAD_COUNT );
Thread[] threads = new Thread[ HTTPThread.THREAD_COUNT ];
for( int i = 0; i < HTTPThread.THREAD_COUNT; i++ ){
threads[ i ] = new Thread( new HTTPThread( httpClient ) );
}
for( Thread thread : threads ){
thread.start();
}
for( Thread thread : threads ){
thread.join();
}
httpClient.close();
System.out.println( "Average response time: " + calAverage( HTTPThread.times ) + " milliseconds." );
}
Класс HTTPThread:
public HTTPThread( CloseableHttpClient httpclient ){
this.httpclient = httpclient;
context = HttpClientContext.create();
}
public void run(){
String format = randomRequest();
start.countDown();
try{
start.await();
}
catch( InterruptedException e ){
e.printStackTrace();
}
boolean resp = false;
long timeMillis = System.currentTimeMillis();
try{
// create new httpPost request with url of his class
HttpPost httpPost = new HttpPost( "http://192.168.1.229:8080/flightcache/flightcache" );
// create params and add it to httpPost
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add( new BasicNameValuePair( "json_req", format ) );
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity( paramList );
httpPost.setEntity( formEntity );
// execute request and save response
CloseableHttpResponse response = httpclient.execute( httpPost, context );
HttpEntity entity = response.getEntity();
resp = entity.getContent().available() > 0;
response.close();
httpclient.close();
// return the response
}
catch( Exception e ){
e.printStackTrace();
}
long end = System.currentTimeMillis() - timeMillis;
if( !resp ){
System.out.println( "Response was empty." );
}
if( end <= 0 ){
times.add( 1L );
}
else{
times.add( end );
}
}
Копая через ваш код, HttpClient закрывается, прежде чем другие потоки смогут получить доступ к их соединению
поскольку все они используют одного и того же клиента, HttpClient # close() должен быть после присоединения потоков