写点什么

架构师训练营第七周作业

用户头像
关注
发布于: 2020 年 11 月 08 日

作业:

用你熟悉的编程语言写一个 Web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 www.baidu.com。

答案:

import lombok.AllArgsConstructor;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
/**
* Created by leo on 2020/11/8.
*/
public class Main {
public static void main(String[] args) throws InterruptedException {
final String url = args[0];
Integer totalCount = Integer.parseInt(args[1]);
Integer concurrency = Integer.parseInt(args[2]);
final Integer loopCount = totalCount / concurrency;
final List<Long> costTimeList = Collections.synchronizedList(new ArrayList<Long>());
final CountDownLatch countDownLatch = new CountDownLatch(concurrency);
ExecutorService executorService = Executors.newFixedThreadPool(concurrency);
for (int i = 0; i < concurrency; i++) {
executorService.execute(new PressTask(url, loopCount, costTimeList, countDownLatch));
}
countDownLatch.await();
Collections.sort(costTimeList);
Long totalCostTime = 0L;
for (Long costTime : costTimeList) {
totalCostTime += costTime;
}
System.out.println("平均响应时间:" + totalCostTime / costTimeList.size() + "ms");
System.out.println("95%响应时间:" + costTimeList.get(totalCount - ((Double) (totalCount * 0.95)).intValue()) + "ms");
System.exit(0);
}
}
@AllArgsConstructor
class PressTask implements Runnable {
private String url;
private Integer loopCount;
private List<Long> costTimeList;
private CountDownLatch countDownLatch;
private static HttpClient httpClient;
static {
RequestConfig config = RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(config)
.setMaxConnTotal(100)
.setMaxConnPerRoute(100).build();
}
@Override
public void run() {
for (int i = 0; i < loopCount; i++) {
try {
Long costTime = doRequest(url);
costTimeList.add(costTime);
} catch (IOException e) {
e.printStackTrace();
}
}
countDownLatch.countDown();
}
public static Long doRequest(String url) throws IOException {
HttpGet httpGet = new HttpGet(url);
Date startTime = new Date();
httpClient.execute(httpGet);
Date endTime = new Date();
long costTime = endTime.getTime() - startTime.getTime();
return endTime.getTime() - startTime.getTime();
}
}



发布于: 2020 年 11 月 08 日阅读数: 19
用户头像

关注

还未添加个人签名 2018.03.09 加入

还未添加个人简介

评论

发布
暂无评论
架构师训练营第七周作业