为什么在 Nginx 中使用 return 指令时速率限制不起作用?

Way*_*ong 3 nginx openresty

我有以下 nginx 配置:

\n
worker_processes 1;\nerror_log logs/error.log;\nevents {\n   worker_connections 1024;\n}\nhttp {\n   limit_req_zone $request_uri zone=by_uri_6000:10m rate=6000r/s;\n\n   server {\n      listen 80;\n      server_name "openresty.com";\n\n      location = /limit-6000 {\n         limit_req zone=by_uri_6000 nodelay;\n         return 200 "ok"\n      }\n   }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但使用wrk测试时根本不起作用:

\n
wrk -c100 -t10 -d5s http://localhost/limit-6000\nRunning 5s test @ http://localhost/\n  10 threads and 100 connections\n  Thread Stats   Avg      Stdev     Max   +/- Stdev\n    Latency     5.57ms    1.65ms  23.47ms   81.17%\n    Req/Sec     1.81k   495.91     9.27k    99.60%\n  90400 requests in 5.10s, 17.93MB read\nRequests/sec:  17713.29\nTransfer/sec:      3.51MB\n
Run Code Online (Sandbox Code Playgroud)\n

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

\n
      location = /limit-6000 {\n         limit_req zone=by_uri_6000 nodelay;\n         default_type 'application/json';\n         content_by_lua_block {\n             ngx.say('{"code": 0, "msg": "\xe6\x88\x90\xe5\x8a\x9f"}')\n         }\n
Run Code Online (Sandbox Code Playgroud)\n

然后就可以了,可能是什么原因,我在官方文档中没有看到任何解释。

\n

Ale*_*ler 5

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

我相信 ngx_http_limit_req_module 在访问阶段工作。因此,使用 return 指令 ngx_http_limit_req_module 没有任何机会参与游戏。