PoolingAsyncClientConnectionManager HttpAsyncClients 写一个带线程池的工具类
时间: 2023-07-04 13:15:24 浏览: 213
线程池工具类
好的,下面是一个简单的带线程池的HttpAsyncClients工具类的实现,使用了PoolingAsyncClientConnectionManager来提高连接复用和效率:
```java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingAsyncClientConnectionManager;
public class HttpAsyncClientUtils {
private static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 200;
private static final int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 20;
private static final int DEFAULT_SOCKET_TIMEOUT = 5000;
private static final int DEFAULT_CONNECTION_TIMEOUT = 5000;
private static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 5000;
private static final int DEFAULT_THREAD_POOL_SIZE = 10;
private static CloseableHttpAsyncClient httpAsyncClient;
private static ExecutorService threadPool;
static {
PoolingAsyncClientConnectionManager connectionManager = new PoolingAsyncClientConnectionManager();
connectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
connectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);
httpAsyncClient = HttpAsyncClients.custom()
.setConnectionManager(connectionManager)
.build();
httpAsyncClient.start();
threadPool = Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE);
}
public static void execute(HttpUriRequest request, FutureCallback<HttpResponse> callback) {
httpAsyncClient.execute(request, callback);
}
public static void execute(HttpUriRequest request) {
httpAsyncClient.execute(request, null);
}
public static void execute(HttpUriRequest request, FutureCallback<HttpResponse> callback, long timeout, TimeUnit timeUnit) {
httpAsyncClient.execute(request, callback);
threadPool.submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(timeUnit.toMillis(timeout));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
httpAsyncClient.close();
}
}
});
}
}
```
这个工具类中,我们使用了静态代码块来初始化线程池和HttpAsyncClient。我们提供了三个execute方法,其中第一个方法接受一个FutureCallback参数,用于异步接收返回结果;第二个方法是同步执行,不需要传入callback参数;第三个方法除了执行请求外,还会在指定时间后关闭HttpAsyncClient,此时线程池也会被关闭。
阅读全文