可以使用Java的线程池来控制多个实例的并发执行,从而减少等待时间。
下面是使用Apache HttpClient 4.5的示例代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
public class HttpParallelExecutor {
private static final int MAX_TOTAL = 200;
private static final int MAX_PER_ROUTE = 20;
private HttpClient httpClient;
private ExecutorService executorService;
public HttpParallelExecutor() {
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
connManager.setMaxTotal(MAX_TOTAL);
connManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);
this.httpClient = HttpClientBuilder.create().setConnectionManager(connManager).build();
this.executorService = Executors.newFixedThreadPool(MAX_PER_ROUTE);
}
public void execute(HttpRequestBase requestBase) {
executorService.execute(new HttpTask(httpClient, requestBase));
}
private static class HttpTask implements Runnable {
private final HttpClient httpClient;
private final HttpRequestBase requestBase;
public HttpTask(HttpClient httpClient, HttpRequestBase requestBase) {
this.httpClient = httpClient;
this.requestBase = requestBase;
}
@Override
public void run() {
try {
HttpResponse response = httpClient.execute(requestBase);
// 处理响应
} catch (Exception e) {
// 处理异常
} finally {
requestBase.releaseConnection();
}
}
}
}
使用该类来执行GET和POST请求:
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
public class Main {
public static void main(String[] args) throws URISyntaxException, IOException {
HttpParallelExecutor executor = new HttpParallelExecutor();
HttpGet httpGet1 = new HttpGet(new URI("http://example.com/get1"));
HttpGet httpGet2 = new HttpGet(new URI("http://example.com/get2"));
HttpPost httpPost1 = new HttpPost(new URI("http://example.com/post1"));
HttpPost httpPost2 = new HttpPost(new URI("http://example.com/post2"));
httpPost1.setEntity(new StringEntity("Hello, World!"));
httpPost2.setEntity(new StringEntity("Foo bar baz"));
executor.execute(httpGet1);
executor.execute(httpGet2);
executor.execute(httpPost1);
executor.execute(httpPost2);
}
}