import org.apache.hc.client5.http.fluent.Request;
import org.apache.hc.core5.http.HttpResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class WebPressTest{
public static void main(String[] args){
WebPressTestUtils.testURL("https://www.baidu.com", 1000, 100);
}
}
class WebPressTestUtils{
public static void testURL(String url, int requestCount, int concurrent){
List<Long> responseTimeList = Collections.synchronizedList(new ArrayList<Long>());
ExecutorService es = Executors.newFixedThreadPool(concurrent);
AtomicInteger current_concurent = new AtomicInteger( 0);
for(int i=0; i<requestCount; i++){
es.execute(new WebPressTestRunner(url, current_concurent, responseTimeList));
}
es.shutdown();
try {
es.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
}
double responseTimeAvg = average(responseTimeList);
double responseTime95 = percentile(responseTimeList, 0.95);
System.out.print(url+": 并发数量"+concurrent+" 请求数量: "+requestCount +
" 平均响应时间:" + responseTimeAvg + "ms %95响应时间: " + responseTime95 + "ms");
}
public static double average(List<Long> list){
double total = 0.0;
for(long value : list){
total += value;
}
return total / list.size();
}
public static double percentile(List<Long> list,double p){
int n = list.size();
Collections.sort(list);
double px = p*(n-1);
int i = (int)java.lang.Math.floor(px);
double g = px - i;
if(g==0){
return list.get(0);
}else{
return (1 - g) * list.get(i) + g * list.get(i+1);
}
}
}
class WebPressTestRunner implements Runnable {
private String url;
private AtomicInteger current_concurrent;
private List<Long> responseTimeList;
public WebPressTestRunner(String url, AtomicInteger current_concurrent, List<Long> responseTimeList){
this.url = url;
this.current_concurrent = current_concurrent;
this.responseTimeList = responseTimeList;
}
public void run() {
try {
this.current_concurrent.incrementAndGet();
long start = System.currentTimeMillis();
HttpResponse response = Request.get(url).execute().returnResponse();
if(response.getCode() == 200) {
long end = System.currentTimeMillis();
long responseTime = end - start;
responseTimeList.add(responseTime);
}else{
System.out.println("响应失败");
}
this.current_concurrent.decrementAndGet();
} catch (IOException e) {
e.printStackTrace();
this.current_concurrent.decrementAndGet();
}
}
}
评论 (1 条评论)