极客时间架构师训练营 week7 作业
发布于: 2020 年 07 月 22 日
作业:用你熟悉的编程语言写一个 web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 www.baidu.com。
import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;import java.io.IOException;import java.math.BigDecimal;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.concurrent.*;public class PerformanceTest { /** * 用你熟悉的编程语言写一个 web 性能压测工具, * 输入参数:URL,请求总次数,并发数。 * 输出参数:平均响应时间,95% 响应时间。 * 用这个测试工具以 10 并发、100 次请求压测 www.baidu.com。 */ private final ThreadPoolExecutor threadPoolExecutor; private final OkHttpClient okHttpClient; private final String url; private final int requestTotalTime; public PerformanceTest(String url,int concurrency,int requestTotalTime){ this.threadPoolExecutor = new ThreadPoolExecutor(concurrency,20,60, TimeUnit.SECONDS,new LinkedBlockingQueue<>(requestTotalTime)); this.requestTotalTime = requestTotalTime; this.url = url; this.okHttpClient = new OkHttpClient(); } public void test95thPercentile() throws ExecutionException, InterruptedException { long [] requestTimeArray = new long[this.requestTotalTime]; List<Future<Long>> futureList = new ArrayList<>(); for (int i = 0; i < requestTotalTime; i++) { Future<Long> submit = this.threadPoolExecutor.submit(() -> { try { long performance = getPerformance(this.okHttpClient, this.url); System.out.println("请求耗时:"+performance+"ms"); return performance; } catch (IOException e) { e.printStackTrace(); return 100000L; } }); futureList.add(submit); } for (int i = 0; i< futureList.size();i++) { requestTimeArray[i] = futureList.get(i).get(); } Arrays.sort(requestTimeArray); int percentileOf95th = BigDecimal.valueOf(requestTimeArray.length).multiply(new BigDecimal("0.95")).subtract(new BigDecimal(1)).setScale(0,BigDecimal.ROUND_HALF_UP).intValue(); System.out.println("95%响应时间:"+requestTimeArray[percentileOf95th]+"ms"); long sum = Arrays.stream(requestTimeArray).sum(); System.out.println("平均响应时间:"+BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(this.requestTotalTime),0,BigDecimal.ROUND_HALF_UP).longValue()+"ms"); } public long getPerformance(OkHttpClient okHttpClient,String url) throws IOException { Request request = new Request.Builder().url(url).build(); Long startTime = System.currentTimeMillis(); Response execute = okHttpClient.newCall(request).execute(); if(execute.isSuccessful()) { execute.close(); Long endTime = System.currentTimeMillis(); return endTime - startTime; } return 100000L; } public static void main(String[] args) throws ExecutionException, InterruptedException { PerformanceTest performanceTest = new PerformanceTest("https://www.baidu.com",10,100); performanceTest.test95thPercentile(); }}
95%响应时间:398ms平均响应时间:63ms
划线
评论
复制
发布于: 2020 年 07 月 22 日阅读数: 50
好名字
关注
还未添加个人签名 2018.09.08 加入
还未添加个人简介
评论 (1 条评论)