架构师训练营第 7 周作业
发布于: 2020 年 07 月 22 日
用你熟悉的编程语言写一个 web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 www.baidu.com
一、代码
package com.study.architect.homework.week07;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpException;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.methods.GetMethod;import java.io.IOException;import java.util.Arrays;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;/** * @ClassName PerformanceTestUtil * @Description 性能测试工具 * @Date 2020/7/20 11:26 * @Version 1.0 **/public class PerformanceTestUtil { private static final String URL = "http://www.baidu.com"; public static void main(String[] args) { // 并发10 performanceTest(100, 10); // 并发100 performanceTest(100, 100); } private static void performanceTest(int totalRequest, int threads) { long[] responseTimeArr = new long[totalRequest]; ExecutorService executorService = Executors.newFixedThreadPool(threads); AtomicInteger atomicInteger = new AtomicInteger(0); for (int i = 0; i < threads; i++) { executorService.submit(new Runnable() { @Override public void run() { for (int i = 0; i < totalRequest/threads; i++) { long responseTime = requestUrl(); responseTimeArr[atomicInteger.getAndIncrement()] = responseTime; } } }); } while (atomicInteger.get() != totalRequest); executorService.shutdownNow(); int totalTime = 0; for (long responseTime : responseTimeArr) { totalTime += responseTime; } System.out.println("================并发数(" + threads + ")=================="); System.out.println("平均响应时间(毫秒):" + totalTime/totalRequest); Arrays.sort(responseTimeArr); System.out.println("95%响应时间(毫秒):" + responseTimeArr[(int)(totalRequest * 0.95)]); } private static void connectUrl(String url) { HttpClient client = new HttpClient(); GetMethod getMethod = new GetMethod(url); getMethod.setRequestHeader("User_Agent", "Mozilla/5.0(Windows NT 6.1;Win64;x64;rv:39.0) Gecko/20100101 Firefox/39.0"); try { int statusCode = client.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { System.out.println("Wrong"); } } catch (HttpException e) { System.out.println("Please check your provided http address!"); e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { getMethod.releaseConnection(); } } private static long requestUrl() { long startTime = System.currentTimeMillis(); connectUrl(URL); long endTime = System.currentTimeMillis(); return endTime - startTime; }}
二、输出结果
划线
评论
复制
发布于: 2020 年 07 月 22 日阅读数: 54
养乐多
关注
还未添加个人签名 2019.11.12 加入
还未添加个人简介
评论