暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

openresty统计ip并将超过阀值的ip写入redis列表

原创 Shyai 2022-11-21
268

–获取cookie
local clientip = ngx.var.remote_addr
–设置redis的key过期时间
local ip_time_out = 60
–设置单位时间内的频率
local ip_max_count = 6

–连接redis
local redis = require “resty.redis”
local conn = redis:new()
ok, err = conn:connect(“127.0.0.1”,6379)
conn:auth(123456)
conn:select(6)
conn:set_timeout(2000)

–测试reds连接是否成功
if not ok then
goto FLAG
end

–获取单位时间内IP的访问次数
ip_count, err = conn:get("-COUNT-"…clientip)

–判断IP是否为空,如为空,则redis存入该IP
if ip_count == ngx.null then
res, err = conn:set("-COUNT-"…clientip, 1)
res, err = conn:expire("-COUNT-"…clientip, ip_time_out)
else
– 判断IP访问是否大于设定的频率
if tonumber(ip_count) >= ip_max_count then
– 大于设定频率则写入list
res, err = conn:rpush(‘test’, clientip)
else
– IP次数加1。
res, err = conn:incr("-COUNT-"…clientip)
end
end

–关闭redis连接
::FLAG::
local ok, err = conn:close()
~

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论