lua_code_cache on; lua_shared_dict my_limit_count_store 10M; server { listen 81; root D:/publish/Mall/Admin; location / { ccess_by_lua_block { -- ngx.header["Content-Type"] = "application/json" local limit_count = require "resty.limit.count" local cjson = require "cjson" -- 1秒内只能有20个请求 local lim, err = limit_count.new("my_limit_count_store", 100, 1) local key = ngx.var.uri local delay, err = lim:incoming(key, true) -- ngx.say(delay) if not delay then if err == "rejected" then ngx.say(cjson.encode({code=-1})) return ngx.exit(429) end end -- ngx.say("success") ngx.status = ngx.HTTP_OK } try_files $uri $uri/ /index.html; if ($request_filename ~* ^.*?.(html|htm)$) { add_header Cache-Control "private, no-store, no-cache, must-revalidate, proxy#-revalidate"; } } }
如果超出了就反向代理到其它地方:
server { listen 1003; location / { access_by_lua_block { ngx.header["Content-Type"] = "application/json" local limit_count = require "resty.limit.count" local cjson = require "cjson" ngx.var.backend = "127.0.0.1:8060" local lim, err = limit_count.new("my_limit_count_store", 2, 1) local key = ngx.var.uri local delay, err = lim:incoming(key, true) if not delay then if err == "rejected" then ngx.var.backend = "11.6.182.42:1001" end end } proxy_pass http://$backend/; log_by_lua_block { ngx.log(ngx.ERR, "backend_dynamic: ", ngx.var.backend) } } }