Skip to content

Instantly share code, notes, and snippets.

@qixiaobo
Created July 24, 2018 08:59
Show Gist options
  • Save qixiaobo/2f04c8040044740582124cf6c2907338 to your computer and use it in GitHub Desktop.
Save qixiaobo/2f04c8040044740582124cf6c2907338 to your computer and use it in GitHub Desktop.
redis lua openresty
local ip = ngx.var.remote_addr
local redis_connect_timeout = 1000
local redis_host = "192.168.12.203"
local redis_port = 6379
local redis_prefix = "sms:"
local redis_white_list_key = redis_prefix .. "white"
local redis_black_list_key = redis_prefix .. "black:"
local redis_limit_key = redis_prefix .. "limit:"
local redis_limit_mode_key = redis_prefix .. "mode"
local now = os.time()
local time = os.date("%H:", now)
local date = os.date("%m%d", now)
local expire_time_in_second = 3600
local expire_date_in_second = 172800
local expire_black_ip_in_second = 86400
local expire_limit_mode_in_second = 86400
local black_list_threshold = 50
local limit_mode_threshold = 600
local is_in_white = false
local header_x_verify = "X-VERIFY"
local redis = require "resty.redis-util"
local red = redis:new({
host = redis_host,
port = redis_port,
db_index = 0,
password = nil,
timeout = redis_connect_timeout,
keepalive = 60000,
pool_size = 100
});
local rlt, err = red:sismember(redis_white_list_key, ip)
if rlt == 1 then
is_in_white = true
else
rlt, err = red:exists(redis_black_list_key .. ip)
if rlt == 1 then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
end
local ip_key = redis_limit_key .. time .. ip
rlt, err = red:set(ip_key, 1, "EX", expire_time_in_second, "NX")
if not rlt then
rlt, err = red:incr(ip_key)
if (rlt >= black_list_threshold and is_in_white == false) then
red:set(redis_black_list_key .. ip, 1, "EX", expire_black_ip_in_second, "NX")
ngx.log(ngx.NOTICE, "black ip found!")
end
end
local date_key = redis_limit_key .. date
rlt, err = red:set(date_key, 1, "EX", expire_date_in_second, "NX")
if not rlt then
rlt, err = red:incr(date_key)
if rlt >= limit_mode_threshold then
--red:set(redis_limit_mode_key, 1, "EX", expire_limit_mode_in_second, "NX")
ngx.req.set_header(header_x_verify, "f6car")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment