目录
Nginx限流
Windows版 - Nginx安装
CMD启动
Microsoft Windows [版本 10.0.18363.1256]
(c) 2019 Microsoft Corporation。保留所有权利。
C:\Users\Administrator>E:
E:\>cd nginx-1.18.0
E:\nginx-1.18.0>start nginx
# 查看启动情况
E:\nginx-1.18.0>tasklist /fi "imagename eq nginx.exe"
映像名称 PID 会话名 会话# 内存使用
========================= ======== ================ =========== ============
nginx.exe 6576 Console 1 7,436 K
nginx.exe 17768 Console 1 7,500 K
nginx.exe 13652 Console 1 7,232 K
nginx.exe 14192 Console 1 7,536 K
# 查看端口占用
E:\nginx-1.18.0>netstat -ano | findstr 0.0.0.0:80
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 17768
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING 14192
TCP 0.0.0.0:8075 0.0.0.0:0 LISTENING 21764
TCP 0.0.0.0:8076 0.0.0.0:0 LISTENING 21764
# 快速停止nginx
E:\nginx-1.18.0> nginx -s stop
# 杀死所有Nginx进程
E:\nginx-1.18.0>taskkill /f /t /im nginx.exe
成功: 已终止 PID 23132 (属于 PID 17768 子进程)的进程。
成功: 已终止 PID 17768 (属于 PID 6576 子进程)的进程。
成功: 已终止 PID 6576 (属于 PID 23536 子进程)的进程。
访问Nginx: http://localhost/
IP限制
- 添加Controller方法
- 网关层配置(修改Host文件和nginx.conf文件)
- 配置Nginx限流规则
流程
- 修改 C:\Windows\System32\drivers\etc\hosts -> www.eddie-training.com = localhost 127.0.0.1
- 修改nginx -> 将步骤1中的域名,添加到路由规则当中。 配置文件地址: E:\nginx-1.18.0\conf\nginx.conf
修改 nginx.conf 配置 (重要部分)
点击查看
# 自定义配置
# 根据IP地址限制速度
limit_req_zone $binary_remote_addr zone=iplimit:20m rate=1r/s;
server {
server_name www.eddie-training.com;
location /access_limit/ {
proxy_pass http://127.0.0.1:10086/;
# 基于IP地址限制
limit_req zone=iplimit burst=2 nodelay;
}
}
}
代码部分
点击查看
com.example.springcloud.controller.Controller
// Nginx专用
// 1. 修改host文件 -> www.eddie-training.com = localhost 127.0.0.1
// (127.0.0.1 www.eddie-training.com)
// 2. 修改nginx -> 将步骤1中的域名,添加到路由规则当中
// 配置文件地址: E:\nginx-1.18.0\conf\nginx.conf
//
// 重新加载nginx(Nginx处于启动) => nginx -s reload
@GetMapping("/nginx")
public String nginx() {
log.info("Nginx success");
return "success";
}
PostMan
www.eddie-training.com/access_limit/nginx
在不停请求时候, 偶尔会出现503情况, 是因为缓冲区满了!
返回:
<html>
<head>
<title>503 Service Temporarily Unavailable</title>
</head>
<body>
<center>
<h1>503 Service Temporarily Unavailable</h1>
</center>
<hr>
<center>nginx/1.18.0</center>
</body>
</html>
连接数限制
- 配置单机限流(类似IP限流)
- 添加Controller方法(耗时接口)
- 配置Nginx限流规则
- IP限流与Conn限流共同作用
修改 nginx.conf 配置
点击查看
配置太长了,如需要可留言!
代码部分
点击查看
com.example.springcloud.controller.Controller
@GetMapping("/nginx-conn")
public String nginxConn(@RequestParam(defaultValue = "0") int secs) {
try {
Thread.sleep(1000 * secs);
} catch (Exception e) {
}
return "success";
}
PostMan
www.eddie-training.com/access_limit/nginx-conn?secs=10
每个IP地址最多保持1个连接 (在10秒内)
分别在 PostMan 和 浏览器 使用GET请求测试
后者测试的返回504错误码