Node.js DNS缓存
Node.js默认不会缓存DNS信息,如果需要发大量请求时,使用带缓存的dns.lookup
可以提高性能。
lookup只支持http,https不会生效
示例
使用http模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| var http = require('http'); var dns = require('dnscache')({ enable: true, ttl: 300, cachesize: 1000 });
var options = { hostname: 'www.baidu.com', port: 80, path: '/fe0a164b-06f9-4d27-a689-c554e69a9d82.jpg', method: 'GET', lookup: dns.lookup };
var req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.on('data', (chunk) => { });
res.on('end', () => { console.log('No more data in response.'); }); });
req.on('error', (e) => { console.log(`problem with request: ${e.message}`); });
req.end();
|
使用request模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| var request = require('request'); var dns = require('dnscache')({ enable: true, ttl: 300, cachesize: 1000 });
request = request.defaults({ lookup: dns.lookup });
request.get('http://www.baidu.com/fe0a164b-06f9-4d27-a689-c554e69a9d82.jpg', function (error, response, body) { if (error) return console.error('request failed:', error);
console.log(`STATUS: ${response.statusCode}`); console.log(`HEADERS: ${JSON.stringify(response.headers)}`); });
|
参考
【1】