nginx嵌入lua做接口保护流量限制
2023-06-13 09:12:28 时间
nginx嵌入lua限制每秒每分钟请求接口次数
在nginx层限制API每秒以及每分钟的请求次数,防止进程被打满。
保护接口
nginx.conf文件
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
# 设置纯 Lua 扩展库的搜寻路径(';;' 是默认路径)
lua_package_path "/data/www/code/nginx+lua/config/lua_p/?.lua;;";
# 设置 C 编写的 Lua 扩展模块的搜寻路径(也可以用 ';;')
lua_package_cpath "/data/www/code/nginx+lua/config/lua_p_c/?.so;;";
# 缓存大小5m
lua_shared_dict url_limit 5m;
server {
listen 8080;
location /limiter {
lua_code_cache off;
content_by_lua_file ./config/lua/limiter.lua;
}
}
}
limiter.lua文件
ngx.header.content_type = "text/html; charset=utf-8";
local method = ngx.req.get_method();
local curl = ngx.md5(ngx.var.request_uri);
local request_uri_without_args = ngx.re.sub(ngx.var.request_uri, "\\?.*", "");
local match = string.match;
local ngxmatch = ngx.re.match;
--限流计数
local function limit_url_check(key, s, m)
local localkey = key;
local yyy_limit = ngx.shared.url_limit;
--每分钟限制
local key_m_limit = localkey .. os.date("%Y-%m-%d %H:%M", ngx.time());
--每秒限制
local key_s_limit = localkey .. os.date("%Y-%m-%d %H:%M:%S", ngx.time());
local req_key, _ = yyy_limit:get(localkey);
local req_key_s, _ = yyy_limit:get(key_s_limit);
local req_key_m, _ = yyy_limit:get(key_m_limit);
--每秒处理
if req_key_s then
yyy_limit:incr(key_s_limit, 1);
if req_key_s > s then
return false;
end
else
yyy_limit:set(key_s_limit, 1, 60);
end
--每分钟处理
if req_key_m then
yyy_limit:incr(key_m_limit, 1);
if req_key_m > m then
return false;
end
else
yyy_limit:set(key_m_limit, 1, 85);
end
return true;
end
local url, err = ngx.re.match(request_uri_without_args, "/limiter");
if url then
if not limit_url_check("limiter", 5, 15) then
ngx.say('{"code": 1000,"msg":当前访问的用户过多,请稍后再试!"}');
ngx.exit(200);
return;
end
end
相关文章
- 保护电路之过流过压过温保护
- 【Android 安全】使用 360 加固宝加固应用 ( 购买高级加固服务 | 设置资源加固 | 设置 SO 文件保护配置 | 设置 SO 防盗用文件配置 | 反编译验证加固效果 )
- 企业保护API安全迫在眉睫
- 如何使用镭速保护云存储数据安全
- 控制SQL Server访问控制:保护数据安全的必备措施(sqlserver访问)
- 备份:Oracle 11g数据库保护计划(oracle11g备份)
- Linux安全:全盘加密保护你的数据(linux全盘加密)
- 安全MongoDB账号安全:保护你的数据(mongodb帐号)
- 微信官方推出可以保护隐私的微小号服务 可接电话/短信就是资费有点贵
- Linux 安装云锁,实现安全保护(linux安装云锁)
- 安全保护:Linux 密码加密技术介绍(linux密码加密)
- Linux 下实现移动硬盘加密保护数据安全(linux移动硬盘加密)
- 深入剖析Linux特权级:解密操作系统保护机制(linux特权级)
- 环保保护:为Linux添加环境变量(添加环境变量linux)
- 重解密用Redis保护接口安全(接口如何防重redis)
- 利用Oracle数据库触发器实现数据完整性保护(oracle中触发器定义)
- Oracle事务使用回滚操作保护数据安全(oracle事务及回滚)
- Redis 需要认证保护(redis需要加鉴权)
- .htaccess文件保护实例讲解