import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public class HttpStressTest {
public static Map<String, Long> hashMap = new ConcurrentHashMap<>();
public static void main(String[] args) {
long start = System.currentTimeMillis();
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
long startTime = System.currentTimeMillis();
int statusCode = 0;
try {
statusCode = doGetSimple("http://www.baidu.com");
} catch (IOException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
long useTime = endTime - startTime;
System.out.print("useTime" + useTime + " ");
System.out.println();
hashMap.put(UUID.randomUUID().toString(), useTime);
}
});
}
fixedThreadPool.shutdown();
while (true) {
if (fixedThreadPool.isTerminated()) {
System.out.println((System.currentTimeMillis() - start) + "ms");
System.out.println("执行完毕");
AtomicReference<Long> allTime = new AtomicReference<>(0l);
List<Long> nineFiveTime = new ArrayList<>();
AtomicInteger i = new AtomicInteger();
hashMap.forEach((k, v) -> {
allTime.updateAndGet(v1 -> v1 + v);
nineFiveTime.add(v);
});
nineFiveTime.sort(Comparator.comparingLong(Long::longValue));
System.out.println("平均响应时间:" + allTime.get() / 100 + "ms");
System.out.println("95%响应时间:" + nineFiveTime.get(95) + "ms");
break;
}
}
}
public static int doGetSimple(String url) throws IOException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
int result = 0;
httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
response = httpClient.execute(httpGet);
result = response.getStatusLine().getStatusCode();
return result;
}
}
评论