import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class PerformanceTest {
public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
int requestCount=100;//请求总次数
int concurrency =10;//并发数
String url="https://www.baidu.com/";
ExecutorService executorService = Executors.newFixedThreadPool(concurrency); //创建线程池
List resultList = Collections.synchronizedList(new ArrayList<Long>());//创建线程安全的list
//创建局部内部类
class RunRequest implements Runnable{
@Override
public void run() {
CloseableHttpClient cClient=null;
CloseableHttpResponse cResponse=null;
try {
Thread.sleep((long)(2000*Math.random()));//请求随机间隔,以防请求过快
long startTime=System.currentTimeMillis();//记录开始时间
cClient=HttpClients.createDefault();//创建HttpClient实例
cResponse = cClient.execute(new HttpGet(url));//发起请求
if(200==cResponse.getStatusLine().getStatusCode()) {
long endTime=System.currentTimeMillis();//记录结束时间
resultList.add(endTime-startTime);//计算本地请求的时间间隔,并存入集合
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
cResponse.close();
cClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
RunRequest runR=new RunRequest();
for(int i=0;i<requestCount;i++) {
executorService.execute(runR);//利用线程池中的线程运行Runnable方法
}
//重复检查是否所有的线程都运行完毕
while(true) {
if(((ThreadPoolExecutor)executorService).getActiveCount()==0) {
System.out.println("所有的子线程都结束了!");
executorService.shutdown();
break;
}
Thread.sleep(1000);
}
System.out.println("成功的请求数量:"+resultList.size());
resultList.sort(Comparator.comparingLong(Long::longValue));//集合排序
long sum=0;//计算响应时间总和
for(int i=0;i<resultList.size();i++) {
sum+=(long)(resultList.get(i));
}
System.out.println("平均响应时间:"+sum/resultList.size()+"ms");
System.out.println("95%响应时间:"+resultList.get(50)+"ms");
}
}
评论