写一个httpclient处理高并发的工具类
时间: 2023-09-11 18:11:40 浏览: 55
好的,以下是一个简单的Java Http Client的高并发工具类,使用了线程池来实现:
```java
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
private static final CloseableHttpClient HTTP_CLIENT = HttpClients.createDefault();
private static final ExecutorService THREAD_POOL = Executors.newFixedThreadPool(100);
private static final RequestConfig REQUEST_CONFIG = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(1000)
.setSocketTimeout(5000)
.build();
public static String executeHttpGet(String url) throws IOException {
HttpGet httpget = new HttpGet(url);
httpget.setConfig(REQUEST_CONFIG);
HttpResponse response = HTTP_CLIENT.execute(httpget);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
}
public static void executeHttpGetAsync(String url, HttpCallback callback) {
THREAD_POOL.execute(new Runnable() {
@Override
public void run() {
try {
String result = executeHttpGet(url);
callback.onSuccess(result);
} catch (IOException e) {
callback.onFailure(e);
}
}
});
}
public static void shutdown() {
try {
HTTP_CLIENT.close();
} catch (IOException e) {
e.printStackTrace();
}
THREAD_POOL.shutdown();
try {
if (!THREAD_POOL.awaitTermination(60, TimeUnit.SECONDS)) {
THREAD_POOL.shutdownNow();
}
} catch (InterruptedException e) {
THREAD_POOL.shutdownNow();
}
}
public interface HttpCallback {
void onSuccess(String result);
void onFailure(Exception e);
}
}
```
这个工具类中包含了一个同步的HTTP GET请求方法和一个异步的HTTP GET请求方法。异步方法使用了回调函数,在请求完成之后通过回调函数返回结果或异常。注意需要确保线程池和HttpClient被正确释放。