LoginSignup
3
0

More than 1 year has passed since last update.

Node.jsでのaxiosによるhttpリクエスト時にKeepAliveを設定して高速化

Posted at

概要

  • Node.jsでaxiosでのhttpリクエスト時にKeelAliveを設定することで処理時間がどの程度短縮できるか試した際のメモ
    • Node.js 19.0.0以前はKeepAliveはデフォルトで無効、19.0.0以降であればデフォルトで有効となっているらしい

環境

  • Typescript 5.0.2
  • Node.js 18.15.0

サンプルコード

  • 必要なnpmパッケージのインストール
$ npm i axios http https
  • axiosを利用してhttpsリクエストを行うClientクラスを作成し、Mainクラスにより複数回リクエスト実行する
sample.ts
import axios, { AxiosRequestConfig } from "axios";
import http from "http";
import https from "https";

// axiosによるhttpリクエスト用
class Client {

  // コネクションの再利用するためのメンバ変数を定義(今回利用しているのhttpsのみ)
  private httpAgent: any;
  private httpsAgent: any;

  constructor() {
    this.httpAgent = new http.Agent({ keepAlive: true });
    this.httpsAgent = new https.Agent({ keepAlive: true });
  }

  public async get() {
    const url = "https://example.com//";
    const config: AxiosRequestConfig = {
      httpAgent: this.httpAgent,
      httpsAgent: this.httpsAgent,
    };

    await axios.get(url, config); // KeepAliveを有効化して引数に渡す
  }
}

// メイン処理用クラス
class Main {
  public async execute() {
    const client: Client = new Client();
    for (let i = 0; i < 10; i++) {
      const startTime = performance.now();
      await client.get();
      const endTime = performance.now();
      console.log(endTime - startTime); // 処理時間を計測(ms)
    }
  }
}

(async () => {
  await new Main().execute();
})();

実行結果(Node.js 18.15.0)

  • 処理を実行してKeepAliveあり、なしの状態を比較してみる
$ npx ts-node src/sample.ts

KeepAlive設定あり

  • 最初の1リクエストでのみTCPコネクション確立の処理が行われおり、以降はコネクションの再利用がされているため処理時間が短縮されている
525.0759160015732
121.82095799967647
126.890625
126.20208300091326
123.89316600002348
123.1732080001384
126.44858399964869
123.4158330000937
126.21420799940825
122.48204099945724

KeepAlive設定なし

  • サンプルコードの axios.get を行う際に、configの設定を行わないでリクエストを実施する
await axios.get(url); // configなし
  • リクエストごとにTCPコネクション確立と破棄が行われいるためKeepAlive設定ありに比べ処理時間がかかっている
531.7899999991059
590.0455419998616
474.6150839999318
456.53095899894834
465.33424999937415
576.2037090007216
562.0905410014093
589.6257500015199
485.87058299966156
593.1784170009196

Node.js 19.0.0 以降の場合

環境

  • Typescript 5.0.2
  • Node.js 19.0.0

実行結果

  • サンプルコードの axios.get を行う際に、configの設定を行わないでリクエストを実施する
await axios.get(url); // configなし
  • configを渡さなくてもKeepAliveが有効化されており、2回目以降のリクエストの処理時間が短縮されている
513.0798749998212
124.72891600057483
124.05337500013411
124.73337499983609
130.4447919987142
124.54537499882281
124.06837500073016
121.77483300119638
121.46916599944234
121.095708001405

参考

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0