要配置服务器支持长连接(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或站点配置中:http { keepalive_timeout 15s; # 超时时间 keepalive_requests 100; # 单连接最大请求数 } -
优化连接池(反向代理场景)
与后端服务的长连接:
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
Node.js (Express) 配置
-
显式设置 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。
关键参数说明
| 参数 | 作用 |
|---|---|
KeepAliveTimeout |
空闲连接保持时间(超时后关闭)。 |
MaxKeepAliveRequests |
单个连接处理的最大请求数(防资源耗尽)。 |
keepalive_timeout (Nginx) |
同 Apache 的 KeepAliveTimeout。 |
keepalive_requests (Nginx) |
同 Apache 的 MaxKeepAliveRequests。 |
keepalive (Nginx upstream) |
后端连接池大小。 |
性能优化建议
- 超时时间:根据业务调整(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 或连接池配置合理。
通过以上配置,可显著减少 TCP 握手次数,提升高并发场景性能。生产环境建议通过 Nginx/Apache 管理长连接,而非应用层直接处理。
图片来源于AI模型,如侵权请联系管理员。作者:酷小编,如若转载,请注明出处:https://www.kufanyun.com/ask/287143.html

