local REDIS_HOST = "127.0.0.1"
local REDIS_PORT = "6379"
local REDIS_CONN_TIMEOUT = 3
local WHITEIPS_KEY = "ip_white"
local BLACKIPS_KEY = "ip_black"
local LIMITIPS_KEY = "ip_limit"
local ip = ngx.var.remote_addr
local redis = require "resty.redis";
local red=redis:new();
function ignoreWhitelist(ip)
local exists = red:exists(WHITEIPS_KEY);
if tonumber(exists) == 1 then
exists = red:sismember(WHITEIPS_KEY,ip);
if tonumber(exists) == 1 then
ngx.log(ngx.INFO," this is white ip ");
return true;
end
end
return false;
end
function checkBlacklist(ip)
local exists = red:exists(BLACKIPS_KEY);
if tonumber(exists) == 1 then
exists = red:sismember(BLACKIPS_KEY,ip);
if tonumber(exists) == 1 then
ngx.log(ngx.INFO," this is black ip ");
return true;
end
end
return false;
end
function limitIpFrequency(ip, times)
local exists = red:exists(LIMITIPS_KEY..ip);
ngx.log(ngx.INFO," exists ",exists);
if tonumber(exists) == 0 then
red:zincrby(LIMITIPS_KEY..ip,1,ip);
red:expire(LIMITIPS_KEY..ip,60);
else
local count = red:zscore(LIMITIPS_KEY..ip,ip);
ngx.log(ngx.INFO,count);
if count then
if tonumber(count) > times then
return true;
end
end
red:zincrby(LIMITIPS_KEY..ip, 1,ip);
end
return false;
end
ngx.log(ngx.DEBUG,"remote_addr is ",ip);
red:set_timeout(REDIS_CONN_TIMEOUT);
local ok,err = red:connect(REDIS_HOST,REDIS_PORT);
if not ok then
ngx.log(ngx.INFO,"redis connection error ");
else
local hit = false;
flg = ignoreWhitelist(ip);
if flg==false then
flg = checkBlacklist(ip);
if flg==true then
return ngx.exit(ngx.HTTP_NOT_FOUND);
else
flg = limitIpFrequency(ip,5);
if flg==true then
return ngx.exit(ngx.HTTP_NOT_FOUND);
end
end
end
end
ok, err = red:set_keepalive(1000,100);
if not ok then
red:close();
end
|
请发表评论