强制net / http使用c-ares而不是getaddrinfo()

时间:2013-10-04 15:27:01

标签: node.js http dns

正如doc所说:

  

dns模块中的所有方法都使用C-Ares,但dns.lookup除外,它在线程池中使用getaddrinfo(3)。

但是,nethttp模块始终使用dns.lookup。有没有办法改变这个? getaddrinfo是同步的,池只允许4个并发请求。

1 个答案:

答案 0 :(得分:4)

在研究之后,似乎唯一的方法是手动执行DNS请求。我使用这样的东西:

var dns = require('dns'),
    http = require('http');

function httpRequest(options, body, done) {
  var hostname = options.hostname || options.host;

  if (typeof(body) === 'function') {
    done = body;
    body = null;
  }

  // async resolve with C-ares
  dns.resolve(hostname, function (err, addresses) {
    if (err)
      return done(err);

    // Pass the host in the headers so the remote webserver
    // can use the correct vhost.
    var headers = options.headers || {};
    headers.host = hostname;
    options.headers = headers;

    // pass the resolved address so http doesn't feel the need to
    // call dns.lookup in a thread pool
    options.hostname = addresses[0];
    options.host = undefined;

    var req = http.request(options, done);

    req.on('error', done);

    if (body)
      req.write(body);

    req.end();
  });
}
相关问题