optimise: create http client by connection pool (#14079)

This commit is contained in:
YuLuo 2024-05-08 11:19:49 +08:00 committed by GitHub
parent c24eca7e1e
commit a3e43fe99b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 31 additions and 2 deletions

View File

@ -22,6 +22,10 @@ public class HttpClientConfig {
private int connectTimeout = 6 * 1000;
private int chunkLength = 8196;
private int maxIdleConnections = 20;
private int keepAliveDuration = 30 * 1000;
private int HTTP_CLIENT_CONNECTION_MANAGER_MAX_PER_ROUTE = 20;
private int HTTP_CLIENT_CONNECTION_MANAGER_MAX_TOTAL = 20;
private int HTTPCLIENT_KEEP_ALIVE_DURATION = 30 * 1000;
@ -57,4 +61,24 @@ public class HttpClientConfig {
public int getChunkLength() {
return chunkLength;
}
public int getMaxIdleConnections() {
return maxIdleConnections;
}
public void setMaxIdleConnections(int maxIdleConnections) {
this.maxIdleConnections = maxIdleConnections;
}
public int getKeepAliveDuration() {
return keepAliveDuration;
}
public void setKeepAliveDuration(int keepAliveDuration) {
this.keepAliveDuration = keepAliveDuration;
}
}

View File

@ -30,6 +30,7 @@ import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
@ -140,11 +141,15 @@ public class OKHttpRestClient implements RestClient {
}
public OkHttpClient createHttpClient(HttpClientConfig httpClientConfig) {
OkHttpClient client = new OkHttpClient.Builder()
return new OkHttpClient.Builder()
.readTimeout(httpClientConfig.getReadTimeout(), TimeUnit.SECONDS)
.writeTimeout(httpClientConfig.getWriteTimeout(), TimeUnit.SECONDS)
.connectTimeout(httpClientConfig.getConnectTimeout(), TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(
httpClientConfig.getMaxIdleConnections(),
httpClientConfig.getKeepAliveDuration(),
TimeUnit.SECONDS))
.build();
return client;
}
}