CentOS7安裝OpenResty以及OpenResty+Lua+Redis 實現IP限流

OpenResty官方下載網站:http://openresty.org/cn/linux-packages.html

安裝OpenResty

yum install -y yum-utils
yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo
yum install -y openresty

創建lua腳本(例子,鏈接:https://www.jianshu.com/p/5f9928c7d730

local function close_redis(red)
    if not red then
        return
    end
    -- 釋放連接(連接池實現),毫秒
    local pool_max_idle_time = 10000
    -- 連接池大小
    local pool_size = 100
    local ok, err = red:set_keepalive(pool_max_idle_time, pool_size)
    local log = ngx_log
    if not ok then
        log(ngx_ERR, "set redis keepalive error : ", err)
    end
end

-- 連接redis
local redis = require('resty.redis')
local red = redis.new()
red:set_timeout(1000)
-- 設置redis連接參數
local ip = "127.0.0.1"
local port = "6379"
local ok, err = red:connect(ip,port)
if not ok then
    return close_redis(red)
end
-- red:auth('123456')
red:select('0')

local clientIP = ngx.req.get_headers()["X-Real-IP"]
if clientIP == nil then
   clientIP = ngx.req.get_headers()["x_forwarded_for"]
end
if clientIP == nil then
   clientIP = ngx.var.remote_addr
end

local incrKey = "user:"..clientIP..":freq"
local blockKey = "user:"..clientIP..":block"

local is_block,err = red:get(blockKey) -- check if ip is blocked
if tonumber(is_block) == 1 then
    ngx.exit(403)
    close_redis(red)
end

inc  = red:incr(incrKey)

if inc < 10 then
   inc = red:expire(incrKey,1)
end
-- 每秒10次以上訪問即視爲非法,會阻止1分鐘的訪問
if inc > 10 then
    --設置block 爲 True 爲1
    red:set(blockKey,1)
    red:expire(blockKey,60)
end

close_redis(red)

在 nginx 配置文件的 http 段添加 lua 腳本

http {
        lua_package_path        "/usr/local/openresty/lualib/resty/redis.lua;";
}

在server 段的 location 中添加

server {
        location / {
            access_by_lua_file "/etc/openresty/access_by_redis.lua";
        }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章