压测作业
package com.artifact.course;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
public class WebPerformanceTester {
private static void testPerformance(String url, int totalReqCount, int concurrentCount){
List<Long> list = sendRequestAndGetResponseTime(url, totalReqCount, concurrentCount);
Long totalTime = list.stream().reduce((a,b)-> a+b).get();
Object[] sortResponseArray = list.stream().sorted().toArray();
System.out.println("Average response time : " + totalTime/totalReqCount + "ms");
int index = Double.valueOf(totalReqCount*0.95).intValue();
System.out.println("95% response time : " + sortResponseArray[index].toString() + "ms");
}
private static List<Long> sendRequestAndGetResponseTime(String url, int totalReqCount, int concurrentCount){
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100);
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(concurrentCount, totalReqCount, 10, TimeUnit.SECONDS, workQueue);
CountDownLatch latch = new CountDownLatch(totalReqCount);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
List<Long> list = new LinkedList<Long>();
for (int i = 0; i < totalReqCount; i++){
threadPoolExecutor.submit(new Runnable() {
@Override
public void run() {
try {
long start = System.currentTimeMillis();
CloseableHttpResponse response = httpClient.execute(buildHttpRequest(url));
//平均响应时间,95%响应时间
long duration = System.currentTimeMillis() - start;
list.add(duration);
} catch (IOException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
threadPoolExecutor.shutdownNow();
return list;
}
private static HttpUriRequest buildHttpRequest(String url){
HttpGet httpgets = new HttpGet(url);
httpgets.setHeader("charset", StandardCharsets.UTF_8.name());
RequestConfig requestConfig = RequestConfig.custom().build();
httpgets.setConfig(requestConfig);
return httpgets;
}
public static void main(String[] args){
if (args != null && args.length == 3){
String url = args[0];
String totalReqCount = args[1];
String concurrentCount = args[2];
testPerformance(url, Integer.valueOf(totalReqCount), Integer.valueOf(concurrentCount));
}
}
}
评论 (1 条评论)