我的电脑是mac,所以我就说一下mac的安装方法:
1、使用brew install wrk命令来安装
2、本地写一个spring-boot服务,写一个controller代码来使用一下wrk,具体代码如下所示:
package com.share.java.http;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
@RestController
@Slf4j
public class ConnectionPoolTest {
@GetMapping("/pool/wrong1")
public String wrong1(){
CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager())
.evictIdleConnections(60L, TimeUnit.SECONDS).build();
try(CloseableHttpResponse response = closeableHttpClient.execute(new HttpGet("http://127.0.0.1:8080/httpclientnotreuse/test"))){
return EntityUtils.toString(response.getEntity());
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@GetMapping("/httpclientnotreuse/test")
public String test(){
return "OK";
}
}
上述代码的依赖是:
org.apache.httpcomponents httpclient 4.5.13
3、使用wrk来进行压测,这里使用1并发1连接来压测10s,具体命令如下:
wrk -c1 -t1 -d 10s http://localhost:8080/pool/wrong1
wrk的参数介绍:
-c, --connections: total number of HTTP connections to keep open with
each thread handling N = connections/threads
-d, --duration: 持续时间, 例:2s, 2m, 2h
-t, --threads: 线程数
-s, --script: 脚本 LuaJIT script, 参阅 scriptING
-H, --header: 添加 HTTP header 到请求, 例: "User-Agent: wrk"
--latency: print detailed latency statistics
--timeout: 请求未收到响应的超时时间
压测的结果:
结果分析:
- Avg 平均值: 每次测试的平均值
- Stdev 标准偏差 :结果的离散程度,越高说明越不稳定
- Max 最大值: 最大的一次结果
- +/- Stdev 正负一个标准差占比: 结果的离散程度,越大越不稳定项目
- Latency:可以理解为响应时间
- Req/Sec:每个线程每秒钟的完成的请求数
4、代码的表现
使用命令 jstack 65912 | grep evictor可以看到有大量Connection的线程出现,且不会被销毁,等待60秒之后就连接处于 CLOSE_WAIT 状态,最终彻底关闭
lsof -nP -i4TCP:8080 | wc -l 其中8080代表的我的服务运行在8080端口



