写点什么

性能压测工具 -JAVA

用户头像
关注
发布于: 2021 年 01 月 08 日
性能压测工具-JAVA

题目

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

实现代码

public class LoadTester {    private static final long REQUEST_FAILED_TIME = -1L;    private static CopyOnWriteArrayList<Long> results = new CopyOnWriteArrayList<>();    private static ExecutorService executor = Executors.newCachedThreadPool();    public static void main(String[] args) throws InterruptedException {        doTest("https://www.baidu.com/", 10);        doTest("https://www.baidu.com/", 100);    }
/** * @param concurrentRequestThreads 并发请求数量 * @param address http地址 */ private static void doTest(String address, int concurrentRequestThreads) throws InterruptedException { CyclicBarrier cyclicBarrier = new CyclicBarrier(concurrentRequestThreads); CountDownLatch latch = new CountDownLatch(concurrentRequestThreads); for (int i = 0; i < concurrentRequestThreads; i++) { executor.submit(() -> { try { //等待并发 cyclicBarrier.await(); long timeElapsed = sendRequest(address); results.add(timeElapsed); } catch (Exception e) { e.printStackTrace(); } finally { latch.countDown(); } }); } latch.await(); System.out.println("并发测试,数量======================= " + concurrentRequestThreads); //排除失败请求,计算平均响应时间 double avgTime = results.stream().filter(time -> time != REQUEST_FAILED_TIME).mapToLong(Long::longValue).average().getAsDouble(); System.out.println("平均响应时间为===> " + avgTime); long failedCount = results.stream().filter(time -> time == REQUEST_FAILED_TIME).count(); System.out.println("失败请求数===> " + failedCount); //计算95%响应时间 List<Long> successfulResults = results.stream().filter(time -> time != REQUEST_FAILED_TIME).collect(Collectors.toList()); int index = (int) (0.95 * successfulResults.size()); long time = successfulResults.get(index); System.out.println("95%响应时间为===> " + time); results.clear(); }

/** * 对目标地址发起请求,成功返回消耗时间(ms),失败返回-1 * @param address http请求地址 * @return */ private static long sendRequest(String address) { long startTime = System.currentTimeMillis(); String content = HttpUtils.get(address, null); if (null == content || content.length() == 0) { return REQUEST_FAILED_TIME; } System.out.println(content); long endTime = System.currentTimeMillis(); return endTime - startTime; }
}
复制代码

执行结果截图



用户头像

关注

还未添加个人签名 2018.04.29 加入

还未添加个人简介

评论

发布
暂无评论
性能压测工具-JAVA