Day 1273:架构师训练营作业(w07)

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

Java类如下,numOfConcurrency是并发数,numOfRequests为请求数。利用CountDownLatch来确保请求都执行之后再结束。

import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpRequest;
import lombok.SneakyThrows;

import java.net.URI;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Perf {
    private String url;
    private int numOfRequests;
    private int numOfConcurrency;
    public Perf(String url, int numOfRequests, int numOfConcurrency) {
        this.url = url;
        this.numOfRequests = numOfRequests;
        this.numOfConcurrency = numOfConcurrency;
    }

    @SneakyThrows
    public long[] collect() {
        HttpClient client = HttpClient.newHttpClient();

        CountDownLatch count = new CountDownLatch(numOfRequests);
        ExecutorService executorService = Executors.newFixedThreadPool(numOfConcurrency);
        long[] responseTime = new long[numOfRequests];
        for (int i = 0; i < numOfRequests; i++) {
            final int k = i;
            executorService.execute(() -> {
                HttpRequest request = HttpRequest.newBuilder().uri(URI.create(url)).build();
                responseTime[k] = System.currentTimeMillis();
                client.send(request, null);
                responseTime[k] = System.currentTimeMillis() - responseTime[k];
                count.countDown();
            });
        }
        count.await();
        return responseTime;
    }

}

你可能感兴趣的:(Day 1273:架构师训练营作业(w07))