nginx重新整理——————http请求的11个阶段中的preaccess[十四]

前言

简单整理一下preaccess。

正文

主要是介绍一下上文提及到的limit_req以及limit_conn。

里面是http_limit_conn_module 默认编译进去。

生效范围:

  1. 全部的workder 进程

  2. 进入preaccess 阶段前不生效

  3. 限制的有效性取决于key的设计: 依赖postread 阶段的realip模块取到真实的ip。

limit_conn 指令:

syntax : limit_conn_zone key zone=name:size;
default: 无
context: http

限制并发连接数:
syntax: limit_conn zone number
default: --
Context: http,server,location

限制发生时的日志级别:
syntax: limit_conn_log_level info|notice|warn|error;
default: error
Context: http,server,location

限制发生时向客户端返回的错误码

syntax: limit_conn_status code;
default: limit_conn_status 503;
context:" http,server,location

例子:

这里limit_conn_zone 可以看到名字为addr,然后key 是addr,分配了10m的内存空间。

limit_conn_status 表示限制的时候返回500。 limit_conn_log_level 错误等级设置为警告。

然后limit_rate 表示了限制速率为50字节每秒。那么limit_conn addr 1;,表示使用addr 这个配置,并且并发数量设置为1。

那么访问一下。

因为这里限制了连接数为1,且是50k,那么其实只有开两个终端,那么一定有一个会返回500的。

那么如何限制每个客户端每秒请求处理的请求数量?

生效阶段 ngx_http_preaccess_pathase 阶段

模块: http_limit_req_module

默认编译金nginx,通过--without-http_limit_req_module 禁用功能
生效算法: leaky bucket 算法

生效范围:

  1. 全部worker 进程
  2. 进入preaccess阶段前不生效

syntax: limit_req_zone key zone=name:size rate=rate;

context http

限制并发连接数:

syntax: limit_req zone=name [burst=namber] [nodelay];
context: http server location

syntax: limit_req_log_level info|notice|warn|error;
default: limit_req_log_level error;
context: http,server,location

限制发生时向客户端返回的错误码:

syntax: limit_red_status code
default: limit_red_status 503;
context: http,server,location
例子:

这里限制了,每分钟请求两次。

然后可以设置一下burst 这个同的大小。

这里加了一个burst=3 nodelay,那么就可以额外请求3个,但是这个额外的3个优先级较低,如果有其他的用户访问,那么会处理其他的。

如果把nodelay去掉,不会立马出现错误,那么就会出现等待。

下一节access 阶段。

posted @ 2022-05-03 21:00  敖毛毛  阅读(65)  评论(0编辑  收藏  举报