我正在使用httpcomponents 4.1.2并且ThreadSafeClientConnManager用完了连接。似乎没有任何方法可以释放连接,这与旧的公共HttpClient不同。我的目标是让一些并发线程对URL进行HTTP POST。任何人都知道如何'释放'连接?或者我应该采取不同的方式吗?
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class HttpThread implements Runnable
{
private static ThreadSafeClientConnManager cm;
private static HttpClient httpClient;
static
{
cm = new ThreadSafeClientConnManager();
cm.setDefaultMaxPerRoute( 10 );
cm.setMaxTotal( 100 );
httpClient = new DefaultHttpClient( cm );
}
private String id;
private int iterations;
public HttpThread( String id, int iterations )
{
this.id= id;
this.iterations = iterations;
}
@Override
public void run()
{
long start = System.currentTimeMillis();
for( int i = 0; i < this.iterations; i++ )
{
HttpPost post = new HttpPost( "http://127.0.0.1:7001/in/iServlet" );
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add( new BasicNameValuePair( "p1", "0123456789" ) );
nvps.add( new BasicNameValuePair( "p2", "7" ) );
nvps.add( new BasicNameValuePair( "p3", "80027-48taPS4lQVu7q6RjEA40kg-1207276200-75-2-1-0" ) );
nvps.add( new BasicNameValuePair( "p4", "1-30--1-2-_60--2-Y-RED,XL__2-30-5-3-A-" ) );
try
{
post.setEntity( new UrlEncodedFormEntity( nvps, HTTP.UTF_8 ) );
System.out.println("before post: " + i);
HttpResponse response = httpClient.execute( post );
System.out.println("after post: " + i);
}
catch( Exception e )
{
e.printStackTrace();
}
finally
{
}
}
long stop = System.currentTimeMillis();
System.out.println( this.id + " finished: " + (stop - start) + " ms" );
}
}
我的司机是:
public class ThreadTest
{
private ExecutorService executor = Executors.newCachedThreadPool();
protected void spawnThreads( int numberOfThreads, int iterations )
{
for( int i = 1; i <= numberOfThreads; i++ )
{
HttpThread thread = new HttpThread( "thread-" + i, 100 );
executor.execute( thread );
System.out.println( "Launching: thread-" + i + " for: " + iterations + " iterations" );
}
}
public static void main(String[] args)
{
ThreadTest t= new ThreadTest();
t.spawnThreads( 1, 100 );
}
}
我的输出是:
Launching: thread-1 for: 100 iterations
before post: 0
after post: 0
before post: 1
after post: 1
before post: 2
after post: 2
before post: 3
after post: 3
before post: 4
after post: 4
before post: 5
after post: 5
before post: 6
after post: 6
before post: 7
after post: 7
before post: 8
after post: 8
before post: 9
after post: 9
before post: 10
答案 0 :(得分:2)
您需要将以下代码添加到run方法的try块中以释放内部资源:
Entity entity = response.getEntity();
if(entity != null) entity.getContent().close();