request-statistics.lua
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了request-statistics.lua,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2476字,纯文字阅读大概需要4分钟。
内容图文
--[[ 实现请求统计,并且将单位时间内异常次数达到阀值的请求加入到黑名单中 -- ]] -- 获取共享内存 local limit_req_store = ngx.shared.limit_req_store --过载保护策略总开关,若开关关闭,则全部策略失效local overload_protection_switch = limit_req_store:get("overload_protection_switch") if (overload_protection_switch ~= niland overload_protection_switch == "N") then ngx.log(ngx.INFO, "nginx limit strategy has been shutdown.") returnend--获取返回状态码local status = ngx.status --获取请求urilocal uri = ngx.var.uri ngx.log(ngx.DEBUG, "current request uri:", uri, ", http status code:", status) local count --记录当前请求的异常次数local uri_last_decay_time_key="cur_time:"..uri --记录当前请求上一次衰减时间节点的 keylocal black_list_key = "black_list:"..uri --记录异常次数达到上限时被加入黑名单的 URI 的 keylocal os_cur_time = os.time() --获取当前系统时间,单位是秒local cur_uri = "cur:"..uri --记录请求异常次数的 key,不能直接用 uri 做 key,会和resty-limit-multiple-strategy.lua文件中的key 冲突--衰减时间内最大异常次数local max_fail_time= limit_req_store:get("period_max_fail_time") if (max_fail_time == nilor max_fail_time == 0) then max_fail_time = 50end ngx.log(ngx.DEBUG,"nginx config period_max_fail_time:",max_fail_time) --衰减时间,所有与过期时间相关的设置单位都是秒local decay_time= limit_req_store:get("period_time") if (decay_time == nilor decay_time == 0) then decay_time = 20end--异常请求加入blacklist的有效时间,单位是秒local black_list_time = limit_req_store:get("black_list_survival_time") if (black_list_time == nilor black_list_time == 0) then black_list_time = 300end--err_code 默认为执行限流策略时的返回码,不需要后续逻辑处理if status == err_code thenreturnend--只统计400以上的返回异常if status >= 400then count= limit_req_store:get(cur_uri) if count == nilthen limit_req_store:set(cur_uri,1) limit_req_store:set(uri_last_decay_time_key,os_cur_time) count = 1else--获取当前异常次数的值 count = limit_req_store:incr(cur_uri,1) end--print("count-----:",count)if count >= tonumber(max_fail_time) then ngx.log(ngx.ERR, "nginx current request uri:", uri," fail time is up to the max_fail_time,and will be added to black_list.") limit_req_store:set(black_list_key,1,black_list_time) limit_req_store:delete(cur_uri) limit_req_store:delete(uri_last_decay_time_key) returnendlocal time = limit_req_store:get(uri_last_decay_time_key) time = os_cur_time-time if time >= tonumber(decay_time) then--math.ceil()函数用户取整 count = math.ceil(count/2) ngx.log(ngx.DEBUG, "nginx current request uri:", uri," fail time was be decayed,current count:", count) limit_req_store:set(cur_uri,count) limit_req_store:set(uri_last_decay_time_key,os_cur_time) endend
原文:https://www.cnblogs.com/koushr/p/5873441.html
内容总结
以上是互联网集市为您收集整理的request-statistics.lua全部内容,希望文章能够帮你解决request-statistics.lua所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。