架构师训练营第七周作业
发布于: 2020 年 07 月 22 日
作业:用你熟悉的编程语言写一个 web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 www.baidu.com。
压测工具类代码如下:
@Slf4j
public class TestTool {
public static void main(String[] args) throws InterruptedException {
test("https://www.baidu.com/", 100, 10);
}
public static void test(String url, int requestTotalCount, int concurrency) throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10000, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(100000));
executor.prestartAllCoreThreads();
CountDownLatch countDownLatch = new CountDownLatch(requestTotalCount);
Map<Integer, Future<Long>> futureMap = IntStream.range(0, requestTotalCount)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> executor.submit(new RequestThread(url, countDownLatch))));
countDownLatch.await();
List<Long> responseTimeList = futureMap.entrySet().stream()
.mapToLong(entryset -> {
try {
return entryset.getValue().get();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return 0L;
}).boxed().collect(Collectors.toList());
OptionalDouble optionalDouble = responseTimeList.stream().mapToLong(i -> i).average();
log.error("----------avg response time:{}ms", optionalDouble.orElse(0.));
List<Long> sortResponseTimeList = responseTimeList.stream().sorted().collect(Collectors.toList());
int index = BigDecimal.valueOf(0.95).multiply(new BigDecimal(requestTotalCount)).intValue();
log.error("----------95% response time:{}ms", sortResponseTimeList.get(index));
log.error(JSONUtils.toJSON(sortResponseTimeList));
executor.shutdown();
log.error("-------main thread finished");
}
private static class RequestThread implements Callable<Long> {
private String url;
private CountDownLatch countDownLatch;
public RequestThread(String url, CountDownLatch countDownLatch) {
this.url = url;
this.countDownLatch = countDownLatch;
}
@Override
public Long call() {
long startTime = System.currentTimeMillis();
try {
HttpUtil.get(url);
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
countDownLatch.countDown();
}
return System.currentTimeMillis() - startTime;
}
}
}
复制代码
压测结果如下:
----------avg response time:148.05ms
----------95% response time:1395ms
复制代码
划线
评论
复制
发布于: 2020 年 07 月 22 日阅读数: 36
斌
关注
还未添加个人签名 2018.05.19 加入
还未添加个人简介
评论