resty.limit.count 模塊介紹:php
resty.limit.count 模塊就是限制接口單位時間的請求數,
This module depends on lua-resty-core模塊,因此要在openresty 的http標籤端添加html
nginx
init_by_lua_block {
require "resty.core"
}nginx
同時resty.limit.count模塊是在OpenResty 1.13.6.1+ 引入的centos
openresty下開啓resty.limit.count此模塊的流程以下:
1.要開啓resty.core openresty內核模塊ide
[root@VM_82_178_centos ~]# grep -C 1 'resty.core' /usr/local/openresty/nginx/conf/nginx.conf init_by_lua_block { require "resty.core" }
注意:resty.core 此模塊只能放到openresty的http標籤,且只容許存在一個ui
2.nginx vhost配置文件:lua
[root@VM_82_178_centos vhost]# cat /usr/local/openresty/nginx/conf/vhost/limit_count.conf server { listen 80; server_name 01limit.count.com; index index.html index.htm index.php; root /data/www/test; location / { access_by_lua_file /usr/local/openresty/nginx/conf/limit_lua/limit.count.lua; default_type 'text/html'; #content_by_lua 'ngx.say("hello world")'; access_log /data/wwwlog/01ip_access.log ; } }
3.配置resty.limit.count 模塊的lua腳本: rest
[root@VM_82_178_centos ~]# cat /usr/local/openresty/nginx/conf/limit_lua/limit.count.lua local limit_count = require "resty.limit.count" -- rate: 100 requests per 1s local lim, err = limit_count.new("my_limit_count_store", 100, 1) if not lim then ngx.log(ngx.ERR, "failed to instantiate a resty.limit.count object: ", err) return ngx.exit(500) end -- use the Authorization header as the limiting key local key = ngx.req.get_headers()["Authorization"] or "public" local delay, err = lim:incoming(key, true) if not delay then if err == "rejected" then ngx.header["X-RateLimit-Limit"] = "100" ngx.header["X-RateLimit-Remaining"] = 0 --每秒請求超過100次的就報錯403 return ngx.exit(403) end ngx.log(ngx.ERR, "failed to limit count: ", err) return ngx.exit(500) end local remaining = err ngx.header["X-RateLimit-Limit"] = "100" ngx.header["X-RateLimit-Remaining"] = remaining
4.ab簡單壓測
採用ab軟件簡單壓測以下:
ab -c 2 -n 50 -t 1 'http://01limit.count.com/2.html'code
19.29.97.11 - - [04/Aug/2019:18:14:14 +0800] "GET /2.html HTTP/1.0" 200 9 "-" "ApacheBench/2.3" 19.29.97.11 - - [04/Aug/2019:18:14:14 +0800] "GET /2.html HTTP/1.0" 200 9 "-" "ApacheBench/2.3" 19.29.97.11 - - [04/Aug/2019:18:14:14 +0800] "GET /2.html HTTP/1.0" 200 9 "-" "ApacheBench/2.3" 19.29.97.11 - - [04/Aug/2019:18:14:14 +0800] "GET /2.html HTTP/1.0" 403 150 "-" "ApacheBench/2.3" 19.29.97.11 - - [04/Aug/2019:18:14:14 +0800] "GET /2.html HTTP/1.0" 403 150 "-" "ApacheBench/2.3" 19.29.97.11 - - [04/Aug/2019:18:14:14 +0800] "GET /2.html HTTP/1.0" 403 150 "-" "ApacheBench/2.3"
到此處resty.limit.count模塊演示完成server