簡體   English   中英

在 node.js 中重用 TCP 連接和節點獲取

[英]Reuse TCP connection with node-fetch in node.js

我正在使用這個 function 來調用外部 API

const fetch = require('node-fetch');

fetchdata= async function (result = {}) {
  var start_time = new Date().getTime();

    let response = await fetch('{API endpoint}', {
      method: 'post',
      body: JSON.stringify(result),
      headers: { 'Content-Type': 'application/json' },
      keepalive: true

    });

  console.log(response) 
  var time = { 'Respone time': + (new Date().getTime() - start_time) + 'ms' };
  console.log(time)
  return [response.json(), time];
  
}

The problem is that i am not sure that node.js is reusing the TCP connection to the API every time i use this function, eventhough i defined the keepalive property.

重復使用 TCP 連接可以顯着提高響應時間
任何建議都將受到歡迎。

https://github.com/node-fetch/node-fetch#custom-agent中所述

const fetch = require('node-fetch');

const http = require('http');
const https = require('https');

const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
const agent = (_parsedURL) => _parsedURL.protocol == 'http:' ? httpAgent : httpsAgent;

const fetchdata = async function (result = {}) {
    var start_time = new Date().getTime();

    let response = await fetch('{API endpoint}', {
        method: 'post',
        body: JSON.stringify(result),
        headers: { 'Content-Type': 'application/json' },
        agent
    });

    console.log(response)
    var time = { 'Respone time': + (new Date().getTime() - start_time) + 'ms' };
    console.log(time)
    return [response.json(), time];

}

Keep-alive 沒有為默認使用的agent啟用,並且當前沒有直接實現到 node-fetch 中,但是您可以輕松地指定一個自定義代理,您可以在其中啟用keep-alive選項:

const keepAliveAgent = new http.Agent({
    keepAlive: true
});

fetch('{API endpoint}', {
     ...
     agent: keepAliveAgent         
});

這是基於 Ilan Frumer 的回答的node-fetch添加keepAlive選項的包裝器

// fetch: add option keepAlive with default true
const fetch = (function getFetchWithKeepAlive() {
  const node_fetch = require('node-fetch');
  const http = require('http');
  const https = require('https');
  const httpAgent = new http.Agent({ keepAlive: true });
  const httpsAgent = new https.Agent({ keepAlive: true });
  return async function (url, userOptions) {
    const options = { keepAlive: true };
    Object.assign(options, userOptions);
    if (options.keepAlive == true)
      options.agent = (parsedUrl => parsedUrl.protocol == 'http:' ? httpAgent : httpsAgent);
    delete options.keepAlive;
    return await node_fetch(url, options);
  }
})();

const response = await fetch('https://github.com/');
const response = await fetch('https://github.com/', { keepAlive: false });

這是基於其文檔的 node-fetch 包裝器:

import nodeFetch, { RequestInfo, RequestInit } from "node-fetch";
import http from "http";
import https from "https";

const httpAgent = new http.Agent({
  keepAlive: true
});

const httpsAgent = new https.Agent({
  keepAlive: true
});

export const fetch = (url: RequestInfo, options: RequestInit = {}) => {
  return nodeFetch(url, {
    agent: (parsedURL) => {
      if (parsedURL.protocol === "http:") {
        return httpAgent;
      } else {
        return httpsAgent;
      }
    },
    ...options
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM