java多次调用外部接口CloseableHttpClient怎么优化及代码
时间: 2023-10-14 22:09:30 浏览: 72
在使用 CloseableHttpClient 调用外部接口时,我们可以通过使用连接池来优化性能,避免频繁创建和销毁连接。
以下是使用连接池的示例代码:
```
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import java.io.IOException;
import java.net.URISyntaxException;
public class HttpClientUtil {
private static PoolingHttpClientConnectionManager connectionManager;
private static CloseableHttpClient httpClient;
static {
connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(100); // 连接池最大连接数
connectionManager.setDefaultMaxPerRoute(20); // 每个路由最大连接数
httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
}
public static CloseableHttpResponse callApi(String url) throws IOException, URISyntaxException {
HttpGet httpGet = new HttpGet(new URIBuilder(url).build());
return httpClient.execute(httpGet);
}
}
```
在以上示例代码中,我们使用了连接池来管理 CloseableHttpClient 的连接,设置了连接池的最大连接数和每个路由的最大连接数,避免了频繁创建和销毁连接。
接下来是使用 HttpClientUtil 调用外部接口的示例代码:
```
import org.apache.http.client.methods.CloseableHttpResponse;
import java.io.IOException;
import java.net.URISyntaxException;
public class ApiCaller {
public static void main(String[] args) throws IOException, URISyntaxException {
for (int i = 0; i < 10; i++) {
CloseableHttpResponse response = HttpClientUtil.callApi("https://www.example.com/api");
// 处理响应
response.close();
}
}
}
```
在以上示例代码中,我们使用 HttpClientUtil 的 callApi 方法调用外部接口,避免了每次调用都创建和销毁 CloseableHttpClient 对象。