架构师训练营第 7 周作业
性能压测的时候,随着并发压力的增加,系统响应时间和吞吐量如何变化,为什么?
用你熟悉的编程语言写一个 web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 www.baidu.com。
程序输出结果如下:
线程数 10 每个线程请求 10 次, 总耗时 14924 平均耗时 149毫秒 百分95的请求小于 610毫秒
代码如下:
package com.jk.test.stress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.apache.http.Consts;
import org.apache.http.client.HttpClient;
import com.jk.test.utils.HttpClient4Utils;
public class StressTest {
/**
* 线程数
*/
private int threadNum;
/**
* 每一个线程请求多少次
*/
private int requestNum;
/**
* 请求测试的URL
*/
private String url;
ArrayList<Integer> requestTimeList = new ArrayList<Integer>();
public StressTest(String url,int threadNum,int requestNum)
{
this.url = url;
this.threadNum = threadNum;
this.requestNum = requestNum;
}
public void start() throws InterruptedException
{
CountDownLatch countDownLatch=new CountDownLatch(threadNum);
for(int i=0;i<threadNum;i++)
{
new Thread(()->{
try{
HttpClient httpClient = HttpClient4Utils.createHttpClient(100, 20, 10000, 2000, 2000);
Map<String, String> params = new HashMap<String, String>();
for(int j=0;j<requestNum;j++)
{
long s = System.currentTimeMillis();
// 请求url
String response = HttpClient4Utils.sendPost(httpClient, url, params, Consts.UTF_8);
s = (System.currentTimeMillis() -s);
synchronized (requestTimeList) {
requestTimeList.add((int)s);
}
}
countDownLatch.countDown();//计数点
}catch (Exception e){
e.printStackTrace();
}
}).start();
}
countDownLatch.await();
statistics();
}
private void statistics()
{
Collections.sort(requestTimeList);
long total = 0;
for(int s:requestTimeList)
{
total+=s;
}
int totalRequest = threadNum*requestNum;
int index95 = (int)(totalRequest*0.95);
System.out.println(String.format("线程数 %s 每个线程请求 %s 次, 总耗时 %s 平均耗时 %s毫秒 百分95的请求小于 %s毫秒", threadNum,requestNum, total, total/totalRequest, requestTimeList.get(index95)));
}
public static void main(String[] args) throws InterruptedException {
StressTest test = new StressTest("https://www.baidu.com",10,10);
test.start();
}
}
评论 (1 条评论)