框架单进程扛并发,瓶颈往往不在 PHP,而在内核参数。下面这几项在 Linux 上基本是必调的。
文件句柄
# 临时生效
ulimit -n 65535
# 永久生效
# /etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
不调这个,连接数一多就报 Too many open files,表现为随机 502 或连接被拒。
TCP 队列
# /etc/sysctl.conf
net.core.somaxconn = 65535 # 已完成握手的队列长度
net.ipv4.tcp_max_syn_backlog = 65535 # 半连接队列
net.ipv4.tcp_tw_reuse = 1 # 复用 TIME_WAIT 连接
net.ipv4.tcp_fin_timeout = 15
net.ipv4.ip_local_port_range = 10000 65000
sysctl -p
内存与连接
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
端口复用(重启不用等)
// Swoole 默认开启 SO_REUSEPORT,重启服务时端口能被立刻复用
// 如果仍报 Address already in use,先确认旧进程真的退出了:
ss -lntp | grep 8848
调完怎么验证
# 当前进程的句柄上限
cat /proc/$(pgrep -f swoole-cli | head -1)/limits | grep "open files"
# 连接数
ss -s
# 内核参数是否生效
sysctl net.core.somaxconn
别乱调这些
tcp_tw_recycle:NAT 环境下会导致连接随机失败,新内核已移除,别开;- 把
somaxconn调到百万级:没有对应业务量只是浪费内存; - 关掉
swap之前先确认真实内存够用。