架构师 0 期 07 周作业

发布于: 2020 年 07 月 21 日

(1)用你熟悉的编程语言写一个 web 性能压测工具,输入参数:URL,请求总次数,并发数。输出参数:平均响应时间,95% 响应时间。用这个测试工具以 10 并发、100 次请求压测 极客时间。

代码:

HttpGet

public static ResponseEntity<?> httpGet(final String url,
final Map<String, String> headerMap) {
final RestTemplate restTemplate = buildRestTemple();
final HttpHeaders headers = buildHeader(headerMap);
final ResponseEntity response = restTemplate.exchange(url,
HttpMethod.GET,
new HttpEntity<>(headers), String.class);
return response;
}
public static ResponseEntity<?> httpDelete(final String url,
final Map<String, String> headerMap) {
final RestTemplate restTemplate = buildRestTemple();
final HttpHeaders headers = buildHeader(headerMap);
final ResponseEntity response = restTemplate.exchange(url,
HttpMethod.DELETE,
new HttpEntity<>(headers), String.class);
return response;
}
private static RestTemplate buildRestTemple() {
final HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
final HttpClient httpClient = HttpClientBuilder.create()
.setRedirectStrategy(new LaxRedirectStrategy()).build();
factory.setHttpClient(httpClient);
final RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1,
new StringHttpMessageConverter(StandardCharsets.UTF_8));
restTemplate.setRequestFactory(factory);
return restTemplate;
}

2.调用方式

@PostMapping("/http/test")
public void testHttpGet(
@RequestParam(value = "url") final String url,
@RequestParam(value = "num") final Integer num,
@RequestParam(value = "concurrentCount") final Integer concurrentCount) {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(concurrentCount);
//配置最大线程数
executor.setMaxPoolSize(concurrentCount);
//配置队列大小
executor.setQueueCapacity(num);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("service-async-task");
//执行初始化
executor.initialize();
final ConcurrentLinkedQueue<Long> queue = new ConcurrentLinkedQueue<>();
for (int i = 0; i < num; i++) {
CompletableFuture<Void> result = CompletableFuture.runAsync(() -> httpGet(url, queue)
, executor);
result.join();
}
final List<Long> timeLists = new ArrayList<Long>(queue);
Collections.sort(timeLists);
int index = (int) (0.95 * num);
System.out.println("P95时间" + timeLists.get(index));
}
void httpGet(final String url, ConcurrentLinkedQueue<Long> timeLists) {
final long start = System.currentTimeMillis();
ResponseEntity<?> result = HttpUtil.httpGet(url, Maps.newHashMap());
final long end = System.currentTimeMillis();
timeLists.add(end - start);
}

使用 postman 调用

请求参数:url=https://time.geekbang.org/ 请求数:1000,并发:5

结果:p95:327

请求参数:url=https://time.geekbang.org/ 请求数:1000,并发:50

结果 p95: 561

请求参数:url=https://horde.geekbang.org/home 请求数:1000,并发:50

结果 p95:321

用户头像

喵呜的小哥哥

关注

还未添加个人签名 2018.10.29 加入

还未添加个人简介

评论

发布
暂无评论
架构师0期07周作业