第七周架构师训练营作业

用户头像
子豪sirius
关注
发布于: 2020 年 07 月 22 日

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



代码见https://github.com/Albertsirius/LoadTest



核心代码是使用Java线程池,建立10个线程的线程池,发起100个请求

public void loadTest() throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(loadTestConfiguration.getConcurrentNum());
for (int count = 0; count < loadTestConfiguration.getRequestNum(); count++) {
executor.execute(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
task.doTask();
statistic.collectResult(System.currentTimeMillis() - start);
countDownLatch.countDown();
}
});
}
countDownLatch.await();
executor.shutdown();
printResult(statistic);
}

保存请求结果和统计测试结果,另外设计了Statistics接口,实现StatisticsImpl保存结果队列

public class StatisticsImpl implements Statistics {
private int requestNum;
private List<Long> resultList;
public StatisticsImpl(int requestNum){
this.requestNum = requestNum;
resultList = new ArrayList<>(requestNum);
}
@Override
public void collectResult(long result) {
synchronized (this) {
resultList.add(result);
}
}
@Override
public long getAverage() {
long sum = 0L;
for(long element : resultList) sum += element;
return sum / requestNum;
}
@Override
public long getPercent(int percent) {
Collections.sort(resultList);
return resultList.get(requestNum * percent / 100);
}
}

Http请求使用Java 11自带的HttpClient:

public class HttpRequestTask implements Task{
private final String httpSchema = "http://";
private String uri;
public HttpRequestTask(String uri) {
this.uri = uri;
}
@Override
public void doTask() {
try {
HttpClient httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
HttpRequest httpRequest = HttpRequest.newBuilder().uri(URI.create(httpSchema + uri)).header("Cache-Control","no-cache,no-store").build();
HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
}catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}



用户头像

子豪sirius

关注

还未添加个人签名 2018.05.03 加入

还未添加个人简介

评论

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