【架构师训练营】week 7 homework
发布于: 2020 年 07 月 22 日
用你熟悉的编程语言写一个 web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 www.baidu.com。
建立 web 性能压测工具类 CocurrentUtil,构建请求方法 doRequest,入参concurrentNums 并发数、reqNums 请求次数、url 请求链接,输出请求总时间,平均响应时间,95% 响应时间。
public class CocurrentUtil { /** * @param concurrentNums 并发数 * @param reqNums 请求次数 * @param url 请求链接 */ public static void doRequest(long concurrentNums, int reqNums,String url) throws Exception{ ExecutorService executor = Executors.newFixedThreadPool((int) concurrentNums); List<Long> timeList = new ArrayList<>(); long startTimeMillis = System.currentTimeMillis(); CountDownLatch latch = new CountDownLatch(reqNums); HttpUtil.get(url); for(int i = 0; i < reqNums; i++) { executor.execute(() ->{ long start = System.currentTimeMillis(); HttpUtil.get(url); latch.countDown(); timeList.add(System.currentTimeMillis()-start); }); } latch.await(); executor.shutdown(); Collections.sort(timeList); long totalCostTimeMillis = System.currentTimeMillis() - startTimeMillis; System.out.println("concurrent threads: " + concurrentNums + ", times: " + reqNums); System.out.println("total cost time(ms): " + totalCostTimeMillis + ",avg time(ms): " + ((double) totalCostTimeMillis / reqNums) + ",95 percent time(ms):" + timeList.get(95*reqNums/100)); }}
main 方法调用,入参分别为10,100,“https://www.baidu.com”。
public static void main(String[] args) { try { CocurrentUtil.doRequest(10,100,"https://www.baidu.com"); } catch (Exception e) { e.printStackTrace(); }}
控制台输出结果
concurrent threads: 10, times: 100total cost time(ms): 3821,avg time(ms): 38.21,95 percent time(ms):205
对比 apache 的 ab 性能压测工具。
> ab -n 100 -c 10 https://www.baidu.com/Server Software: BWS/1.1Server Hostname: www.baidu.comServer Port: 443SSL/TLS Protocol: TLSv1.2,ECDHE-RSA-AES128-GCM-SHA256,2048,128Document Path: /Document Length: 227 bytesConcurrency Level: 10Time taken for tests: 1.219 secondsComplete requests: 100Failed requests: 0Total transferred: 108195 bytesHTML transferred: 22700 bytesRequests per second: 82.03 [#/sec] (mean)Time per request: 121.904 [ms] (mean)Time per request: 12.190 [ms] (mean, across all concurrent requests)Transfer rate: 86.67 [Kbytes/sec] receivedConnection Times (ms) min mean[+/-sd] median maxConnect: 40 95 43.9 84 250Processing: 9 22 16.7 17 100Waiting: 8 22 16.7 17 99Total: 53 117 48.2 101 267Percentage of the requests served within a certain time (ms) 50% 101 66% 131 75% 147 80% 162 90% 198 95% 216 98% 238 99% 267 100% 267 (longest request)
划线
评论
复制
发布于: 2020 年 07 月 22 日阅读数: 53
eazonshaw
关注
还未添加个人签名 2019.04.10 加入
还未添加个人简介
评论