概述http模块源码:https://github.com/nodejs/nod...functioncreateServer(opts,requestListener){returnnewServer(opts,requestListener);}functionrequest(url,options,cb){returnnewClientRequest(url,options,cb);}functionget(url,options,cb){varreq=request(url,options,cb);请求结束();returnreq;}我们不难发现http模块提供了三个主要功能:http.request、http.get、http.createServer。前两个功能主要是创建http客户端,向其他服务器发送请求。http.get只是将get请求发送到http.request的一种便捷方式;而http.createServer是创建Node服务。比如Koa服务框架就是基于http.createServer封装的。http.Agenthttp.Agent主要为http.request、http.get提供代理服务,用于管理http连接的创建、销毁和重用。http.request、http.get默认使用http.globalAgent作为代理。每个请求都是一个“建立连接-数据传输-破坏连接”的过程。Object.defineProperty(module.exports,'globalAgent',{configurable:true,enumerable:true,get(){returnhttpAgent.globalAgent;//默认使用http.globalAgent作为代理},set(value){httpAgent.globalAgent=value;//如果我们想让多个请求复用同一个连接,需要重新定义代理覆盖默认的http.globalAgent}});如果我们想让多个请求重用同一个连接,就需要重新定义agent来覆盖默认的http.globalAgent,我们来看看新建一个agent需要的主要参数有哪些:keepAlive:{Boolean}是否开启keepAlive,多个请求共享一个socket连接,默认为false。maxSockets:{Number}每个主机允许的sockets的最大值,默认值为Infinity。maxFreeSockets:{Number}连接池空闲状态下的最大连接数,只有开启keepAlive时才有效。让http=require('http');constkeepAliveAgent=newhttp.Agent({keepAlive:true,maxScokets:1000,maxFreeSockets:50})http.get({主机名:'localhost',端口:80,路径:'/',agent:keepAliveAgent},(res)=>{//用响应做事});只有向同一个主机和端口发送请求,才能共享同一个keepAlive套接字连接。如果开启了keepAlive,多个请求会被放入队列中等待;如果当前队列为空,则socket处于空闲状态,但不会被销毁,等待下一次请求。使用keepAlive代理有效减少了建立/销毁连接的开销,开发者可以动态管理连接池。大概是这个意思。具体可以参考Node.js官方文档示例https://gitlab.com/fatihadiso...参考https://nodejs.org/docs/lates...http://nodejs.cn/api/http.htm...以上图片来自:https://segmentfault.com/a/11...https://segmentfault.com/a/11...
