Nodejs学习记录:http模块

概览

http模块源码: https://github.com/nodejs/nod…


function createServer(opts, requestListener) {
  return new Server(opts, requestListener);
}

function request(url, options, cb) {
  return new ClientRequest(url, options, cb);
}

function get(url, options, cb) {
  var req = request(url, options, cb);
  req.end();
  return req;
}

我们不难发现,http 模块提供三个主要的函数: http.request, http.get, http.createServer。前两个函数主要是为了创建 http 客户端,向其它服务器发送请求,http.get 只是 http.request 的发送 get 请求的便捷方式;而 http.createServer 是为了创建 Node 服务,比如 Koa 服务框架就是基于 http.createServer 封装的。

http.Agent

《Nodejs学习记录:http模块》

http.Agent 主要是为 http.request, http.get 提供代理服务的,用于管理 http 连接的创建,销毁及复用工作。http.request, http.get 默认使用 http.globalAgent 作为代理,每次请求都是“建立连接-数据传输-销毁连接”的过程,

Object.defineProperty(module.exports, 'globalAgent', {
  configurable: true,
  enumerable: true,
  get() {
    return httpAgent.globalAgent;// 默认使用 http.globalAgent 作为代理
  },
  set(value) {
    httpAgent.globalAgent = value; // 如果我们想让多个请求复用同一个 connection,则需要重新定义 agent 去覆盖默认的 http.globalAgent
  }
});

如果我们想让多个请求复用同一个 connection,则需要重新定义 agent 去覆盖默认的 http.globalAgent,下面我们看一下新建一个agent的需要哪些主要参数:

  • keepAlive:{Boolean} 是否开启 keepAlive,多个请求公用一个 socket connection,默认是 false。
  • maxSockets:{Number} 每台主机允许的socket的最大值,默认值为Infinity。
  • maxFreeSockets:{Number} 处于连接池空闲状态的最大连接数, 仅当开启 keepAlive 才有效。
let http = require('http');
const keepAliveAgent = new http.Agent({ 
    keepAlive: true,
    maxScokets: 1000,
    maxFreeSockets: 50 
})
http.get({
  hostname: 'localhost',
  port: 80,
  path: '/',
  agent: keepAliveAgent 
}, (res) => {
  // Do stuff with response
});

只有向相同的 host 和 port 发送请求才能公用同一个 keepAlive 的 socket 连接,如果开启 keepAlive ,同一时间内多个请求会被放在队列里等待;如果当前队列为空,该 socket 处于空闲状态,但是不会被销毁,等待下一次请求的到来。

使用 keepAlive 代理,有效的减少了建立/销毁连接的开销,开发者可以对连接池进行动态管理。

大体差不多就是这个意思,详细可以看Node.js 官方文档

《Nodejs学习记录:http模块》

参考

https://nodejs.org/docs/lates…
http://nodejs.cn/api/http.htm…
以上图片来自:https://segmentfault.com/a/11…
https://segmentfault.com/a/11…

    原文作者:AlexZ33
    原文地址: https://segmentfault.com/a/1190000017950134
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞