1. 程式人生 > 其它 >OpenResty之resty.limit.count 模組介紹

OpenResty之resty.limit.count 模組介紹

resty.limit.count 模組介紹:

resty.limit.count 模組就是限制介面單位時間的請求數,
This module depends on lua-resty-core模組,所以要在openresty 的http標籤端新增

nginx

init_by_lua_block {
    require “resty.core”
}

同時resty.limit.count模組是在OpenResty1.13.6.1+ 引入的

openresty下開啟resty.limit.count此模組的流程如下:
1.要開啟resty.core openresty核心模組


[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標籤,且只允許存在一個

2.nginx vhost配置檔案:

[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指令碼: **


[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

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模組演示完成