简单 Web 性能压测工具实现(java)

用户头像
梧桐
关注
发布于: 2020 年 12 月 06 日



本程序基于CountDownLatch实现 。

CountDownLatch是一个同步辅助类,它允许一个或多个线程一直等待直到其他线程执行完毕才开始执行。



网络连接线程

public class ConnectThread implements Runnable {
private CountDownLatch latch;
private String url;
private int connectNums;

public ConnectThread(CountDownLatch latch, String url, int connectNums) {
this.latch = latch;
this.url = url;
this.connectNums = connectNums;
}

public void run() {
for (int i = 0; i < connectNums; i++) {
long startTime = System.currentTimeMillis();
try {
HttpGet httpGet = new HttpGet(url);
CloseableHttpClient client = HttpClients.createDefault();
client.execute(httpGet);

long endTime = System.currentTimeMillis();
Press.queue.add((endTime - startTime));
// System.out.println(i+ ":响应时间:" + (endTime - startTime));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
latch.countDown();
}

}

主方法:

public class Press {
private static String url="https://www.baidu.com";
private static int threadNums=10;
private static int connectNums=10;
public static ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue();

public static void main(String[] args) {

ExecutorService executor = Executors.newCachedThreadPool();
CountDownLatch latch = new CountDownLatch (threadNums);

for(int i = 0;i<threadNums;i++){
executor.execute(new ConnectThread(latch,url,connectNums));
}

try {
latch.await();
long result = 0;
ArrayList<Long> list = new ArrayList(Press.queue);
for (Long i : list) {
result += i;
}
Collections.sort(list );
System.out.println("avg time is:" + result / list.size());

Double p95 = list.size() * 0.95;
System.out.println("95% time is:" + list.get(p95.intValue()));

executor.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}



经测试本开发环境

平均响应时间为:337ms

95% 响应时间为:1784ms





用户头像

梧桐

关注

还未添加个人签名 2018.07.06 加入

还未添加个人简介

评论

发布
暂无评论
简单Web 性能压测工具实现(java)