百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

Nginx/Redis Lua实现分布式计数器限流

liebian365 2024-11-14 18:03 17 浏览 0 评论

如果有这么一个场景:实现控制单IP在10秒内(一定时间周期内)只能访问10次(一定次数)的限流功能,该如何来实现?下面介绍两种实现方式

实现一:Nginx Lua实现分布式计数器限流

  • 使用Redis存储分布式访问计数;
  • Nginx Lua编程完成计数器累加及逻辑判断

首先,在Nginx的配置文件中添加location配置块,拦截需要限流的接口,匹配到该请求后,将其转给一个Lua脚本处理。

location = /access/demo/nginx/lua {
            set $count 0;
            access_by_lua_file luaScript/module/ratelimit/access_auth_nginx.lua;
            content_by_lua_block {
                ngx.say("目前访问总数: ", ngx.var.count, "<br>");
                ngx.say("Hello World");
            }
        }

定义access_auth_nginx.lua限流脚本,该脚本会调用一个名为RedisKeyRateLimit.lua的限流计数器脚本,完成针对同一个IP的限流操作。

RedisKeyRateLimit限流计数器脚本代码如下:

---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by xx.
--- DateTime: 2022/2/21 下午8:27
---
local basic = require("luaScript.module.common.basic");
local redisOp = require("luaScript.redis.RedisOperator");

--一个统一的模块对象
local _Module = {}
_Module.__index = _Module;

-- 创建一个新的实例
function _Module.new(self, key)
    local object = {red = nil};
    setmetatable(object, self);

    --创建自定义的Redis操作对象
    local red = redisOp:new();
    basic.log("参数key = "..key);
    red:open();
    object.red = red;
    --object.key = "count_rate_limit:" .. key;
    object.key = key;
    return object;
end

-- 判断是否能通过流量控制
-- true:未被限流;false:被限流
function _Module.acquire(self)
    local redis = self.red;
    basic.log("当前key = "..self.key)
    local current = redis:getValue(self.key);

    basic.log("value type is "..type(current));
    basic.log("当前计数器值 value = "..tostring(current));
    --判断是否大于限制次数
    local limited = current and current ~= ngx.null and tonumber(current) > 10;

    -- 被限流
    if limited then
        basic.log("限流成功,已经超过10次了,本次是第"..current.."次");
        redis:incrValue(self.key);
        return false;
    end

    if not current or current == ngx.null then
        redis:setValue(self.key, 1);
        redis:expire(self.key, 10);
    else
        redis:incrValue(self.key);
    end
    return true
end

-- 取得访问次数
function _Module.getCount(self)
    local current = self.red:getValue(self.key);
    if current and current ~= ngx.null then
        return tonumber(current);
    end
    return 0;
end

-- 归还Redis
function _Module.close(self)
    self.red:close();
end

return _Module;

access_auth_nginx限流脚本如下:

---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by xx.
--- DateTime: 2022/2/21 下午8:44
---
-- 导入自定义模块
local basic = require("luaScript.module.common.basic");
local RedisKeyRateLimit = require("luaScript.module.ratelimit.RedisKeyRateLimit");

--定义出错的JSON输出对象
local errorOut = {errorCode = -1, errorMsg = "限流出错", data = {} };

--获取请求参数
local args = nil;
if "GET" == ngx.var.request_method then
    args = ngx.req.get_uri_args();
elseif "POST" == ngx.var.request_method then
    ngx.req.read_body();
    args = ngx.req.get_post_args();
end

--ngx.say(args["a"]);
--ngx.say(ngx.var.remote_addr);

-- 获取用户IP
local shortKey = ngx.var.remote_addr;

if not shortKey or shortKey == ngx.null then
    errorOut.errMsg = "shortKey 不能为空";
    ngx.say(cjson.encode(errorOut));
    return;
end

-- 拼接计数的Redis Key
local key = "count_rate_limit:ip:"..shortKey;

local limiter = RedisKeyRateLimit:new(key);

local pass = limiter:acquire();

if pass then
    ngx.var.count = limiter:getCount();
    basic.log("access_auth_nginx get count = "..ngx.var.count)
end

limiter:close();

if not pass then
    errorOut.errorMsg = "您的操作太频繁了,请稍后再试.";
    ngx.say(cjson.encode(errorOut));
    ngx.say(ngx.HTTP_UNAUTHORIZED);
end

return;

浏览器访问http://localhost/access/demo/nginx/lua?a=111接口,10秒内多次刷新结果如下:

频繁刷新后的结果

某个时间点Redis中,存入的键-值如下


上述方案,如果是单网关,则不会有一致性问题。在多网关(Nginx集群)环境下,计数器的读取和自增由两次Redis远程操作完成,可能会出现数据一致性问题,且同一次限流需要多次访问Redis,存在多次网络传输,会降低限流的性能

实现二:Redis Lua实现分布式计数器限流

该方案主要依赖Redis,使用Redis存储分布式访问计数,又通过Redis执行限流计数器的Lua脚本,减少了Redis远程操作次数,相对于Nginx网关,保证只有一次Redis操作即可完成限流操作,而Redis可以保证脚本的原子性。架构图如下:

具体实现:

首先,在Nginx的配置文件中添加location配置块,拦截需要限流的接口,匹配到该请求后,将其转给一个Lua脚本处理

location = /access/demo/redis/lua {
  set $count 0;
  access_by_lua_file luaScript/module/rateLimit/access_auth_redis.lua;
  content_by_lua_block {
    ngx.say("目前访问总数: ", ngx.var.count, "<br>");
    ngx.say("Hello World");
  }
}

再来看限流脚本:redis_rate_limit.lua

-- 限流计数器脚本,负责完成访问计数和限流结果判断。该脚本需要在Redis中加载和执行

-- 返回0表示需要限流,返回其他值表示访问次数
local cacheKey = KEYS[1];
local data = redis.call("incr", cacheKey);
local count = tonumber(data);

-- 首次访问,设置过期时间
if count == 1 then
    redis.call("expire", cacheKey, 10);
end

if count > 10 then
    return 0;    -- 0表示需要限流
end

return count;

限流脚本要执行在Redis中,因此需要将其加载到Redis中,并且获取其加载后的sha1编码,供Nginx上的限流脚本access_auth_redis.lua使用。

将redis_rate_limit.lua脚本加载到Redis的命令如下:

# 进入到当前脚本目录
?  rateLimit git:(main) ? cd ~/Work/QDBank/Idea-WorkSpace/About_Lua/src/luaScript/module/rateLimit
# 加载Lua脚本
?  rateLimit git:(main) ? ~/Software/redis-6.2.6/src/redis-cli script load "$(cat redis_rate_limit.lua)"
"5f383977029cd430bd4c98547f3763c9684695c7"
?  rateLimit git:(main) ? 

最后看下access_auth_redis.lua脚本。该脚本使用Redis的evalsha操作指令,远程访问加载在Redis中的redis_rate_limit.lua脚本,完成针对同一个IP的限流。

---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by xuexiao.
--- DateTime: 2022/2/22 下午10:15
---
local RedisKeyRateLimit = require("luaScript.module.rateLimit.RedisKeyRateLimit")
--定义出错的JSON输出对象
local errorOut = {errorCode = -1, errorMsg = "限流出错", data = {} };

--获取请求参数
local args = nil;
if "GET" == ngx.var.request_method then
    args = ngx.req.get_uri_args();
elseif "POST" == ngx.var.request_method then
    ngx.req.read_body();
    args = ngx.req.get_post_args();
end

-- 获取用户IP
local shortKey = ngx.var.remote_addr;
if not shortKey or shortKey == ngx.null then
    errorOut.errMsg = "shortKey 不能为空";
    ngx.say(cjson.encode(errorOut));
    return;
end

-- 拼接计数的Redis key
local key = "redis_count_rate_limit:ip:"..shortKey;

local limiter = RedisKeyRateLimit:new(key);

local passed = limiter:acquire();

-- 通过流量控制
if passed then
    ngx.var.count = limiter:getCount()
end

limiter:close();

-- 未通过流量控制
if not passed then
    errorOut.errorMsg = "您的操作太频繁了,请稍后再试.";
    ngx.say(cjson.encode(errorOut));
    ngx.exit(ngx.HTTP_UNAUTHORIZED);
end

return;

浏览器中访问http://localhost/access/demo/redis/lua?a=999,限流效果同案例一。

通过将Lua脚本加入Redis执行有以下优势:

  • 减少网络开销:只需要一个脚本即可,不需要多次远程访问Redis;
  • 原子操作:Redis将整个脚本作为一个原子执行,无须担心并发,也不用考虑事务;
  • 复用:只要Redis不重启,脚本加载之后会一直缓存在Redis中,其他客户端可以通过sha1编码执行。

相关推荐

4万多吨豪华游轮遇险 竟是因为这个原因……

(观察者网讯)4.7万吨豪华游轮搁浅,竟是因为油量太低?据观察者网此前报道,挪威游轮“维京天空”号上周六(23日)在挪威近海发生引擎故障搁浅。船上载有1300多人,其中28人受伤住院。经过数天的调...

“菜鸟黑客”必用兵器之“渗透测试篇二”

"菜鸟黑客"必用兵器之"渗透测试篇二"上篇文章主要针对伙伴们对"渗透测试"应该如何学习?"渗透测试"的基本流程?本篇文章继续上次的分享,接着介绍一下黑客们常用的渗透测试工具有哪些?以及用实验环境让大家...

科幻春晚丨《震动羽翼说“Hello”》两万年星间飞行,探测器对地球的最终告白

作者|藤井太洋译者|祝力新【编者按】2021年科幻春晚的最后一篇小说,来自大家喜爱的日本科幻作家藤井太洋。小说将视角放在一颗太空探测器上,延续了他一贯的浪漫风格。...

麦子陪你做作业(二):KEGG通路数据库的正确打开姿势

作者:麦子KEGG是通路数据库中最庞大的,涵盖基因组网络信息,主要注释基因的功能和调控关系。当我们选到了合适的候选分子,单变量研究也已做完,接着研究机制的时便可使用到它。你需要了解你的分子目前已有哪些...

知存科技王绍迪:突破存储墙瓶颈,详解存算一体架构优势

智东西(公众号:zhidxcom)编辑|韦世玮智东西6月5日消息,近日,在落幕不久的GTIC2021嵌入式AI创新峰会上,知存科技CEO王绍迪博士以《存算一体AI芯片:AIoT设备的算力新选择》...

每日新闻播报(September 14)_每日新闻播报英文

AnOscarstatuestandscoveredwithplasticduringpreparationsleadinguptothe87thAcademyAward...

香港新巴城巴开放实时到站数据 供科技界研发使用

中新网3月22日电据香港《明报》报道,香港特区政府致力推动智慧城市,鼓励公私营机构开放数据,以便科技界研发使用。香港运输署21日与新巴及城巴(两巴)公司签署谅解备忘录,两巴将于2019年第3季度,开...

5款不容错过的APP: Red Bull Alert,Flipagram,WifiMapper

本周有不少非常出色的app推出,鸵鸟电台做了一个小合集。亮相本周榜单的有WifiMapper's安卓版的app,其中包含了RedBull的一款新型闹钟,还有一款可爱的怪物主题益智游戏。一起来看看我...

Qt动画效果展示_qt显示图片

今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):该程序使用应用程序单窗口,主窗口继承于QMainWindow...

如何从0到1设计实现一门自己的脚本语言

作者:dong...

三年级语文上册 仿写句子 需要的直接下载打印吧

描写秋天的好句好段1.秋天来了,山野变成了美丽的图画。苹果露出红红的脸庞,梨树挂起金黄的灯笼,高粱举起了燃烧的火把。大雁在天空一会儿写“人”字,一会儿写“一”字。2.花园里,菊花争奇斗艳,红的似火,粉...

C++|那些一看就很简洁、优雅、经典的小代码段

目录0等概率随机洗牌:1大小写转换2字符串复制...

二年级上册语文必考句子仿写,家长打印,孩子照着练

二年级上册语文必考句子仿写,家长打印,孩子照着练。具体如下:...

一年级语文上 句子专项练习(可打印)

...

亲自上阵!C++ 大佬深度“剧透”:C++26 将如何在代码生成上对抗 Rust?

...

取消回复欢迎 发表评论: