对于每天执行数千或数百万个请求并需要解决此问题的人:
当在服务器上执行大量请求时,出现getaddrinfo EAI_AGAIN
错误是相当正常的。Node.js本身不执行任何DNS缓存,它将所有与DNS相关的事情委托给操作系统。
您需要知道,每个http/https请求都会执行DNS查找,这可能非常昂贵。为避免此瓶颈和getaddrinfo
错误,您可以实现DNS缓存。
http.request
(以及https)接受一个lookup
属性,默认为dns.lookup()
http.get('http://example.com', { lookup: yourLookupImplementation }, response => {
// do something here with response
});
我强烈建议您使用已经经过测试的模块,而不是自己编写DNS缓存,因为您需要正确处理TTL等其他事项以避免难以跟踪的错误。
我个人使用的是
cacheable-lookup
,这是
got
使用的模块(请参见
dnsCache
选项)。
您可以在特定请求中使用它。
const http = require('http');
const CacheableLookup = require('cacheable-lookup');
const cacheable = new CacheableLookup();
http.get('http://example.com', {lookup: cacheable.lookup}, response => {
});
或者全局地
const http = require('http');
const https = require('https');
const CacheableLookup = require('cacheable-lookup');
const cacheable = new CacheableLookup();
cacheable.install(http.globalAgent);
cacheable.install(https.globalAgent);
注意:请记住,如果请求不是通过Node.js的http/https
模块执行的,则在全局代理上使用.install
对该请求没有任何影响。例如,使用undici
发出的请求。
(Note: 请注意,如果请求不是通过 Node.js 的 http/https 模块执行的,那么在全局代理上使用 .install 对该请求没有任何影响。例如,使用 undici 发出的请求。)
After=nss-lookup.target
? - Melroy van den Berg