配置 Nginx 实现连接超时
在企业网站中, 为了避免同一个客户长时间占用连接, 造成资源浪费, 可设置相应的连接超时参数, 实现控制连接访问时间
使用 Fiddler 工具查看 connection 参数
超时参数
- Keepalive_ timeout
- # 设置连接保持超时时间,- 般可只设置该参数, 默认为 75 秒, 可根据
网站的情况设置, 或者关闭, 可在 http 段, server 段, 或者 location 段
设置
- Client_header_ timeout
- # 指定等待客户端发送请求头的超时时间
- Client_ body_ _timeout
- # 设置请求体读超时时间
更改 Nginx 运行进程数
1. 在高并发场景, 需要启动更多的 Nginx 进程以保证快速响应, 以处理用户的请求, 避免造成阻塞
2. 可以使用 ps aux 命令查看 Nginx 运行进程的个数
3. 更改进程数的配置方法: 配置文件, 修改进程配置参数
4. 修改配置文件的 worker_ _processes 参数
(1) 一般设为 CPU 的个数或者核数
(2) 在高并发情况下可设置为 CPU 个数或者核数的 2 倍
5. 运行进程数多一些, 响应访问请求时, Nginx 就不会临时启动新的进程提供服务, 减少了系统的开销, 提升了服务速度
6. 使用 ps aux 查看运行进程数的变化情况
7. 默认情况, Nginx 的多个进程可能跑在一一个 CPU 上, 可以分配不同的进程给不同的 CPU 处理, 充分利用硬件多 3 核多 CPU
8. 在一台 4 核物理服务器, 可进行以下配置, 将进程进行分配: Worker_ CPU affinity 0001 0010 0100 1000
实例演示
一, Nginx 连接超时演示
修改 nginx.conf 配置文件
- [[email protected] ~]# cd /usr/local/nginx/conf/
- [[email protected] conf]# VIM nginx.conf
- #keepalive_timeout 0;
- keepalive_timeout 65 180;
- # 服务端和客户端的超时时间, 可在 http\server\location 中设置
- client_header_timeout 80;
- # 等待客户端发送请求头部超时时间, 超时会发送 408 错误
- client_body_timeout 80;
- # 请求体超时时间
- [[email protected] conf]# systemctl stop nginx
- [[email protected] conf]# systemctl start nginx
二, Nginx 进程管理演示
第一步: 关闭虚拟机, 添加 CPU
第二步: 查看此时 Nginx 进程信息
- [[email protected] ~]# ps aux | grep nginx
- root 1854 0.0 0.0 20544 608 ? Ss 14:17 0:00 nginx: master process /usr/local/nginx/sbin/nginx
- nginx 1855 0.0 0.0 23072 1392 ? S 14:17 0:00 nginx: worker process
- root 1859 0.0 0.0 112728 972 pts/0 S+ 14:18 0:00 grep --color=auto nginx
第三步: 修改配置文件
- [[email protected] ~]# cd /proc/
- [[email protected] proc]# cat cpuinfo ## 查看 CPU 核心数
- processor : 0 ## 第一个 CPU
- ...
- processor : 1 ## 第二个 CPU
- ...
- [[email protected] proc]# VIM /usr/local/nginx/conf/nginx.conf
- #user nobody;
- worker_processes 2;
- # 修改核数相同或者 2 倍
- worker_cpu_affinity 01 10;
- # 设置每个进程有不同的 CPU 处理
来源: http://www.bubuko.com/infodetail-3289658.html