java&go串行http请求对比

50 阅读1分钟

假设我们有一个需求,先请求接口1,再串行请求接口2,最后得到结果。

    public static void main(String[] args) throws Exception {
        System.setProperty("reactor.netty.ioWorkerCount", "8");
        WebClient client = webClient();
        int n = 5000;
        CountDownLatch latch = new CountDownLatch(n);
        long start = System.nanoTime();
        for (int i = 0; i < n; i++) {
            client.get()
                    .uri("/1")
                    .retrieve()
                    .bodyToFlux(String.class)
                    .flatMap(r1 -> {
                        return client.get()
                                .uri("/3")
                                .retrieve()
                                .bodyToMono(String.class);
                    }).subscribe(v -> {
                        latch.countDown();
                    }, v -> {
                        System.out.println(v);
                        latch.countDown();
                    });
        }
        latch.await();
        System.err.println((System.nanoTime() - start) / 1000000);
    }

    public static WebClient webClient() {
        ConnectionProvider provider = ConnectionProvider.builder("myConnectionPool")
                .maxConnections(20) // 自定义最大连接数
                .pendingAcquireMaxCount(-1) // 自定义挂起获取的最大数量
                .pendingAcquireTimeout(Duration.ofSeconds(100)) // 自定义挂起获取的超时时间
                .build();
        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(HttpClient.create(provider)))
                .baseUrl("http://127.0.0.1:8000")
                .build();
    }
func request() {
	client := &http.Client{
		Timeout: 10 * time.Second,
		Transport: &http.Transport{
			MaxIdleConns:          20,
			MaxIdleConnsPerHost:   20,
			IdleConnTimeout:       90 * time.Second,
			MaxConnsPerHost:       20,
			ExpectContinueTimeout: 1 * time.Second,
		},
	}
	var wg sync.WaitGroup
	wg.Add(5000)
	start := time.Now()
	for i := 0; i < 5000; i++ {
		go httpGet(client, &wg)
	}
	wg.Wait()
	fmt.Println(time.Since(start))

}

func httpGet(client *http.Client, wg *sync.WaitGroup) {
	defer wg.Done()
	resp, err := client.Get("http://127.0.0.1:8000/1")
	if err != nil {
		fmt.Println(err)
	}
	ioutil.ReadAll(resp.Body)

	resp2, err := client.Get("http://127.0.0.1:8000/3")
	if err != nil {
		fmt.Println(err)
	}
	ioutil.ReadAll(resp2.Body)
	defer resp2.Body.Close()
	defer resp.Body.Close()

}

第一组, 请求一个比较稳定的远程接口

javago
4.5593.974s

第二组, 请求本地一个无延时的服务

javago
1.173s160ms