如何避免nodejs express应用中出现太多的http连接

现象

正常情况下,基于nodejs的http通信应用,在发送http.request时不管你是否使用agent和timeout/keepAlive,客户端和服务器之间的连接数不会太多。但下面情况下,在请求频繁时连接数可能会快速增长并且不会释放:

客户端

复制代码
http.request(...)

服务器端

复制代码
express().use("/",(req,res)=>{
    
    return; //不回应

    res.send(`responed by server`);
    res.end();
});

也就是说如果服务端没有正确响应,连接将会一直存在,不管客户端如何调整请求参数。

解决方法

要解决这个问题,有两个地方可以处理:

服务端及时响应请求

复制代码
express().use("/",(req,res)=>{
    res.send(`responed by server`);
    res.end();
});

这种情况下,客户端无论是否使用agent,是否keepAlive,连接数都不会太多。

客户端超时后强制关闭

复制代码
let req = http.request(...)
req.on('timeout', function() {
        console.error("request time out!");
    	//强制关闭连接
        req.destroy();
});

客户端优化

复制代码
const express = require("express");
const http    = require('http');

const agent = new http.Agent({
	keepAlive: true,
	timeout:2000
});

function post(host,port,path,content,callback) {
    var data    = '';
    var options = {
        agent: agent,
        hostname: host,
        port: port,
        path: path,
        method: 'POST',
        timeout:2000,
        headers: {
            'Content-Type': 'application/json; charset=UTF-8',
            'Connection': 'Keep-Alive'
        }
    };
    var req = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
            data = data + chunk;
        });
        res.on('end', () => {
            callback(null,data);
        });
    });

    req.on('error', function(e) {
        callback("error",e);
    });

    //这是重点
    req.on('timeout', function() {
        req.destroy();
        callback("timeout");
    });
    
    req.write(content);
    req.end();
}
相关推荐
qq_429856572 小时前
计算机网络的五层结构(物理层、数据链路层、网络层、传输层、应用层)到底是什么?
网络·计算机网络
奋斗者1号7 小时前
《Crawl4AI 爬虫工具部署配置全攻略》
网络·爬虫
courniche7 小时前
VRRP与BFD在冗余设计中的核心区别:从“备用网关”到“毫秒级故障检测”
网络·智能路由器
艾厶烤的鱼8 小时前
架构-信息安全技术基础知识
网络·架构
Hello.Reader9 小时前
洞悉 NGINX ngx_http_access_module基于 IP 的访问控制实战指南
tcp/ip·nginx·http
muxue1789 小时前
centos 7 网络配置(2):ping命令出现问题
linux·网络·centos
SQingL12 小时前
解决SSLError: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] decryption faile的问题
服务器·网络协议·ssl
山猪打不过家猪12 小时前
(六)RestAPI 毛子(外部导入打卡/游标分页/Refit/Http resilience/批量提交/Quartz后台任务/Hateoas Driven)
网络·缓存
weixin1382339517912 小时前
EN18031测试,EN18031认证,EN18031报告解读
网络
JhonKI13 小时前
【Linux网络】构建与优化HTTP请求处理 - HttpRequest从理解到实现
linux·网络·http