为什么在使用 Nginx 中的 return 指令时速率限制无效?

我有以下 nginx 配置:

worker_processes 1;
error_log logs/error.log;
events {
   worker_connections 1024;
}
http {
   limit_req_zone $request_uri zone=by_uri_6000:10m rate=6000r/s;

   server {
      listen 80;
      server_name "openresty.com";

      location = /limit-6000 {
         limit_req zone=by_uri_6000 nodelay;
         return 200 "ok"
      }
   }
}

但是当我使用 wrk 进行测试时,它根本不起作用:

wrk -c100 -t10 -d5s http://localhost/limit-6000
Running 5s test @ http://localhost/
  10 threads and 100 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     5.57ms    1.65ms  23.47ms   81.17%
    Req/Sec     1.81k   495.91     9.27k    99.60%
  90400 requests in 5.10s, 17.93MB read
Requests/sec:  17713.29
Transfer/sec:      3.51MB

但是,如果我将配置更改为以下内容(实际上我正在使用 openresty):

      location = /limit-6000 {
         limit_req zone=by_uri_6000 nodelay;
         default_type 'application/json';
         content_by_lua_block {
             ngx.say('{"code": 0, "msg": "成功"}')
         }

它就可以正常工作了,是什么原因?在官方文档中没有解释。

点赞
用户2060502
用户2060502

nginxreturn指令在重写阶段起作用,它立即返回结果。

我相信ngx\_http\_limit\_req\_module在访问阶段起作用。因此,使用return指令时,ngx\_http\_limit\_req\_module没有任何机会参与。

2021-04-13 14:08:09