引用的httpclient-4.5.2、httpcore-4.4.4.jar。
一、为什么要用Http连接池
1、降低延迟:如果不采用连接池,每次连接发起Http请求的时候都会重新建立TCP连接(经历3次握手),用完就会关闭连接(4次挥手),如果采用连接池则减少了这部分时间损耗,别小看这几次握手,本人经过测试发现,基本上3倍的时间延迟
2、支持更大的并发:如果不采用连接池,每次连接都会打开一个端口,在大并发的情况下系统的端口资源很快就会被用完,导致无法建立新的连接。
如短连接去做压测,可能会报错:java.net.NoRouteToHostException: Cannot assign requested address。
而我们一般用的长连接是通过添加Keep-Alive头参解决: header.add(new NVPair("Connection", "Keep-Alive"));
而事实上头参中加了此参数只是保持长连接,与建立TCP连接保持的长连接不一样。
在NG上做了一个针对nginx的压测,主要目标是压测nginx,在请求方式上无要求。
如果此时采用NG原始生成默认代码做压测,最大TPS只能到8W,瓶颈主要在重新建立TCP连接,并未到nginx。
修改代码采取以下方式,可以将TPS提高到24W。 在线上压测可以到80W。
package test.http import ch.qos.logback.classic.Level import net.grinder.script.GTest import net.grinder.scriptengine.groovy.junit.GrinderRunner import net.grinder.scriptengine.groovy.junit.annotation.BeforeProcess import net.grinder.scriptengine.groovy.junit.annotation.BeforeThread import org.apache.http.HeaderElement import org.apache.http.HeaderElementIterator import org.apache.http.HttpEntity import org.apache.http.HttpResponse import org.apache.http.client.config.RequestConfig import org.apache.http.client.methods.CloseableHttpResponse