在Node.js中重用带有节点提取的 TCP 连接



我正在使用此函数调用外部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];

}

问题是我不确定每次使用此函数时 node.js 是否重用与 API 的 TCP 连接,即使我定义了 keepalive 属性。

重用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];
}

这是一个基于其文档的节点获取包装器:

import nodeFetch, { RequestInfo, RequestInit, Response } 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 = {}): Promise<Response> => {
return nodeFetch(url, {
agent: (parsedURL) => {
if (parsedURL.protocol === "http:") {
return httpAgent;
} else {
return httpsAgent;
}
},
...options
});
};

默认使用的agent未启用 Keep-alive,并且当前未直接在 node-fetch 中实现,但您可以轻松指定启用keep-alive选项的自定义代理:

const keepAliveAgent = new http.Agent({
keepAlive: true
});
fetch('{API endpoint}', {
...
agent: keepAliveAgent         
});

这里有一个包装器,供node-fetch根据Ilan Frumer的答案添加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 });

最新更新