http模块源码: https://github.com/nodejs/nod...html
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 封装的。node
http.Agent
主要是为 http.request, http.get 提供代理服务的,用于管理 http 链接的建立,销毁及复用工做。http.request, http.get 默认使用 http.globalAgent 做为代理,每次请求都是“创建链接-数据传输-销毁链接”的过程,git
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的须要哪些主要参数:github
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 处于空闲状态,可是不会被销毁,等待下一次请求的到来。segmentfault
使用 keepAlive 代理,有效的减小了创建/销毁链接的开销,开发者能够对链接池进行动态管理。api
大致差很少就是这个意思,详细能够看Node.js 官方文档服务器
https://nodejs.org/docs/lates...
http://nodejs.cn/api/http.htm...
以上图片来自:https://segmentfault.com/a/11...
https://segmentfault.com/a/11...框架