要创建新的套接字连接而不是重用来自连接池的连接,您可以使用Apache AsyncHttpClient的CloseableHttpAsyncClient
类,并在每次请求之前关闭连接。以下是一个简单的示例代码:
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
public class HttpClientExample {
public static void main(String[] args) {
try (CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault()) {
httpclient.start();
// 创建新的套接字连接
HttpGet request1 = new HttpGet("https://example.com");
httpclient.execute(request1, new FutureCallback() {
@Override
public void completed(final HttpResponse response) {
System.out.println(request1.getRequestLine() + "->" + response.getStatusLine());
}
@Override
public void failed(final Exception ex) {
System.out.println(request1.getRequestLine() + "->" + ex);
}
@Override
public void cancelled() {
System.out.println(request1.getRequestLine() + " cancelled");
}
}).get();
// 创建新的套接字连接
HttpGet request2 = new HttpGet("https://example.org");
httpclient.execute(request2, new FutureCallback() {
@Override
public void completed(final HttpResponse response) {
System.out.println(request2.getRequestLine() + "->" + response.getStatusLine());
}
@Override
public void failed(final Exception ex) {
System.out.println(request2.getRequestLine() + "->" + ex);
}
@Override
public void cancelled() {
System.out.println(request2.getRequestLine() + " cancelled");
}
}).get();
} catch (IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我们使用CloseableHttpAsyncClient
创建了一个新的Http客户端,并在每个请求完成后关闭连接。这将导致每次请求都会创建一个新的套接字连接,而不是重用连接池中的连接。