local mysql_host = "ip of mysql server"
local mysql_port = 3306
local database = "dbname"
local username = "user"
local password = "password"
-- update ip_blacklist from mysql once every cache_ttl seconds
local cache_ttl = 1
local mysql_connection_timeout = 1000
local client_ip = ngx.var.real_ip
local ip_blacklist = ngx.shared.ip_blacklist
local last_update_time = ip_blacklist:get("last_update_time");
if last_update_time == nil or last_update_time < ( ngx.now() - cache_ttl ) then
local mysql = require "resty.mysql";
local red = mysql:new();
red:set_timeout(mysql_connect_timeout);
local ok, err, errcode, sqlstate = red:connect{
host = mysql_host,
port = mysql_port,
database = database,
user = username,
password = password,
charset = "utf8",
max_packet_size = 1024 * 1024,
}
if not ok then
ngx.log(ngx.ERR, "mysql connection error while retrieving ip_blacklist: " .. err);
else
new_ip_blacklist, err, errcode, sqlstate = red:query("select ip_addr from ip_blacklist where status = 0 order by create_time desc limit 10000", 100)
if not new_ip_blacklist then
ngx.log(ngx.ERR, "bad result. errcode: " .. errcode .. " sqlstate: " .. sqlstate .. " err: " .. err);
return
end
ip_blacklist:flush_all();
for k1, v1 in pairs(new_ip_blacklist) do
for k2, v2 in pairs(v1) do
ip_blacklist:set(v2,true);
end
end
ip_blacklist:set("last_update_time", ngx.now());
end
end
ngx.say("sync successful");
get_ipblacklist_info.lua
-- 调用URL查看黑名单信息
-- 1万IP消耗不到1.5M ngx.shared内存
-- 获取所有KEY会堵塞别的正常请求对ngx.shared内存的访问,因此只能取少数key展示
require "resty.core.shdict"
ngx.say("total space: " .. ngx.shared.ip_blacklist:capacity() .. "<br/>");
ngx.say("free space: " .. ngx.shared.ip_blacklist:free_space() .. "<br/>");
ngx.say("last update time: " .. os.date("%Y%m%d_%H:%M:%S",ngx.shared.ip_blacklist:get("last_update_time")) .. "<br/>");
ngx.say("first 100 keys: <br/>");
ngx.say("--------------------------<br/>");
ip_blacklist = ngx.shared.ip_blacklist:get_keys(100);
for key, value in pairs(ip_blacklist) do
ngx.say(key .. ": " .. value .. "<br/>");
end
check_realip.lua
if ngx.shared.ip_blacklist:get(ngx.var.real_ip) then
return ngx.exit(ngx.HTTP_FORBIDDEN);
end