上一篇
如何配置服务器长连接?高效性能优化技巧
- 互联网
- 2026-02-08
- 4159
要配置服务器支持长连接(Keep-Alive),需根据服务器软件类型进行调整,以下是主流服务器的配置方法:
Apache 配置
-
启用 Keep-Alive
编辑配置文件(httpd.conf 或虚拟主机文件):
KeepAlive On KeepAliveTimeout 15 # 连接保持时间(秒) MaxKeepAliveRequests 100 # 单个连接最大请求数 -
优化 MPM 模块
根据并发模型调整(如 prefork 或 worker):
<IfModule mpm_prefork_module> StartServers 10 MinSpareServers 10 MaxSpareServers 20 MaxRequestWorkers 150 MaxConnectionsPerChild 1000 </IfModule> -
重启服务
sudo systemctl restart apache2
Nginx 配置
-
调整 keepalive 参数
在 nginx.conf 或站点配置中:
-
优化连接池(反向代理场景)
与后端服务的长连接:
upstream backend { server 127.0.0.1:8080; keepalive 32; # 连接池大小 } server { location / { proxy_pass http://backend; proxy_http_version 1.1; # 必需 proxy_set_header Connection ""; # 清除Connection头 } }
-
重启服务
sudo systemctl restart nginx -
显式设置 HTTP Keep-Alive
const http = require('http'); const server = http.createServer(app); // 设置长连接参数 server.keepAliveTimeout = 15000; // 15秒超时 server.headersTimeout = 16000; // 包头超时 > keepAliveTimeout server.listen(3000);
-
使用反向代理
建议通过 Nginx 管理长连接,而非直接暴露 Node.js。
- 超时时间:根据业务调整(5-30 秒),过长浪费资源,过短失去意义。
- 最大请求数:高并发场景建议限制(如 100-1000),避免单一连接占用过久。
- 监控连接:使用 netstat -anp | grep :80 或 ss -s 检查连接状态。
- 压力测试:用 ab 或 wrk 验证配置效果: ab -k -n 1000 -c 100 http://yourserver.com/ # -k 启用 Keep-Alive
-
502 Bad Gateway
→ 检查反向代理的 proxy_http_version 1.1 和 Connection 头设置。
-
连接泄漏
→ 确保客户端能正常关闭连接,必要时缩小 keepalive_timeout。
-
性能不升反降
→ 检查服务器资源(CPU/内存),确保 MPM 或连接池配置合理。
Node.js (Express) 配置
关键参数说明
| 参数 | 作用 |
|---|---|
| KeepAliveTimeout | 空闲连接保持时间(超时后关闭)。 |
| MaxKeepAliveRequests | 单个连接处理的最大请求数(防资源耗尽)。 |
| keepalive_timeout (Nginx) | 同 Apache 的 KeepAliveTimeout。 |
| keepalive_requests (Nginx) | 同 Apache 的 MaxKeepAliveRequests。 |
| keepalive (Nginx upstream) | 后端连接池大小。 |
性能优化建议
常见问题
通过以上配置,可显著减少 TCP 握手次数,提升高并发场景性能。生产环境建议通过 Nginx/Apache 管理长连接,而非应用层直接处理。