写点什么

架构师训练营 - 第七周作业

用户头像
chenlovehx
关注
发布于: 2020 年 11 月 08 日

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



具体实现代码:

public class PressTool {
public static void main(String[] args) {
new PressTool().press("http://www.baidu.com", 100, 10);
}
public void press(String url, int requestCount, int threadCount) {
ExecutorService threadPool = Executors.newFixedThreadPool(threadCount, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
return thread;
}
});
((ThreadPoolExecutor) threadPool).prestartCoreThread();
long[] requestTime = new long[requestCount];
AtomicInteger requestFailCount = new AtomicInteger(0);
AtomicInteger requestSuccessCount = new AtomicInteger(0);
for (int i = 0; i < requestCount; i++) {
int finalI = i;
threadPool.submit(() -> {
Stopwatch stopwatch = Stopwatch.createStarted();
OkHttpClient client = new OkHttpClient.Builder().build();
Request request = new Request.Builder().url(url).get().build();
try {
Response response = client.newCall(request).execute();
long executeTime = stopwatch.stop().elapsed(TimeUnit.MILLISECONDS);
requestTime[finalI] = executeTime;
if (response.isSuccessful()) {
requestSuccessCount.incrementAndGet();
}
} catch (IOException e) {
requestFailCount.incrementAndGet();
}
});
}
threadPool.shutdown();
while (!threadPool.isTerminated()) {
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
}
}
Arrays.sort(requestTime);
long totalRequestTime = Arrays.stream(requestTime).sum();
System.out.println("共" + requestCount + "个请求,"
+ threadCount + "个线程, 共耗时:" + totalRequestTime + "毫秒。"
+ "请求成功次数:" + requestSuccessCount.get() + ";请求失败次数:" + requestFailCount.get());
System.out.println("平均响应时间为:(ms)" + new BigDecimal(totalRequestTime)
.setScale(4, RoundingMode.HALF_UP)
.divide(new BigDecimal(requestCount)));
System.out.println("95%响应时间为:(ms)" + requestTime[requestTime.length - 5]);
}
}

执行结果为:

共100个请求,10个线程, 共耗时:22553毫秒。请求成功次数:100;请求失败次数:0
平均响应时间为:(ms)225.5300
95%响应时间为:(ms)2075



发布于: 2020 年 11 月 08 日阅读数: 21
用户头像

chenlovehx

关注

还未添加个人签名 2018.04.26 加入

还未添加个人简介

评论

发布
暂无评论
架构师训练营 - 第七周作业