HTTP高并发调优小记

时间:2023-07-20 23:09:38

tomcat服务层

1.修改server.xml

<Connector port="8088" protocol="HTTP/1.1"
maxThreads="1000"
connectionTimeout="60000"
acceptCount="1100"
redirectPort="8443" />

2.修改catalina.bat

set JAVA_OPTS=-Xms1024m -Xmx2048m

Java应用层-Httpclient

1.修改连接池的连接数

static {
LayeredConnectionSocketFactory sslsf = null;
try {
sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
} catch (NoSuchAlgorithmException e) {
logger.error("创建SSL连接失败");
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 设置连接池最大连接数800
cm.setMaxTotal(800);
// 设置最大路由数10
cm.setDefaultMaxPerRoute(10);
}

2.设置失败重试次数

/**
* getHttpClient
* <p>通过连接池管理创建CloseableHttpClient</p>
* @return
*/
private static CloseableHttpClient getHttpClient() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setUserAgent(properties.getProperty("userAgent"))
// 失败重连5次
.setRetryHandler(new DefaultHttpRequestRetryHandler(5, false))
.build();
return httpClient;
}

3.设置连接超时时长

/**
* config
* <p>普通请求配置</p>
* @param httpRequestBase
*/
private static void config(HttpRequestBase httpRequestBase) {
httpRequestBase.setHeader("Accept-Encoding", "gzip,deflate");
// 配置请求的超时设置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(3000)
.setConnectTimeout(3000)
.setSocketTimeout(3000)
.build();
httpRequestBase.setConfig(requestConfig);
}