# 长连接配置 http { # 客户端到Nginx的连接 keepalive_timeout 65s; # 长连接保持时间 keepalive_requests 100; # 单个连接最大请求数 # Nginx到上游服务器的连接 upstream backend { server 192.168.1.10:8080; keepalive 32; # 连接池大小 keepalive_timeout 60s; # 连接保持时间 } # 启用长连接 location / { proxy_http_version 1.1; # 使用HTTP/1.1 proxy_set_header Connection ""; proxy_pass http://backend; } }
场景:1000个并发用户,每个用户10个请求 短连接: - QPS: 1200 requests/sec - 平均响应时间: 85ms - 服务器连接数峰值: 9500 - CPU使用率: 65% 长连接: - QPS: 2800 requests/sec - 平均响应时间: 35ms - 服务器连接数峰值: 180 - CPU使用率: 45%
http { # 优化长连接参数 keepalive_timeout 75s; # 根据业务调整 keepalive_requests 500; # 提高复用次数 # 连接池优化 upstream backend { keepalive 100; # 根据后端容量调整 keepalive_timeout 120s; keepalive_requests 1000; } # TCP优化 tcp_nodelay on; # 禁用Nagle算法 tcp_nopush on; # 优化数据包发送 }
# 监控连接状态 netstat -an | grep :80 | wc -l ss -s | grep -i total # Nginx状态监控 # 在nginx.conf中添加 location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; }
# 根据请求类型选择 map $uri $use_keepalive { default "on"; "~*\.(jpg|png|css|js)$" "on"; # 静态资源用长连接 "/api/transaction" "off"; # 关键交易用短连接 }
# 使用ab测试 # 短连接测试 ab -n 10000 -c 100 -H "Connection: close" http://example.com/ # 长连接测试 ab -n 10000 -c 100 -k http://example.com/ # 使用wrk测试(更好的长连接支持) wrk -t4 -c100 -d30s --latency http://example.com/
最终结论:在大多数生产环境中,合理配置的长连接相比短连接能带来 2-5倍的性能提升,特别是在高并发、小请求场景下效果尤为显著。但需要根据具体业务特点进行精细调优。