Nginx/Redis Lua实现分布式计数器限流
mhr18 2024-11-07 11:05 33 浏览 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编码执行。
相关推荐
- 京东大佬问我,每天新增100w订单数据的分库分表方案
-
京东大佬问我,每天新增100w订单数据的分库分表方案嗯,用户问的是高并发订单系统的分库分表方案,每天新增100万订单。首先,我得理解需求。每天100万订单,那每秒大概是多少呢?算一下,100万除以86...
- MySQL 内存使用构成解析与优化实践
-
在为HULK平台的MySQL提供运维服务过程中,我们常常接到用户反馈:“MySQL内存使用率过高”。尤其在业务高峰期,监控中内存占用持续增长,即便数据库运行正常,仍让人怀疑是否存在异常,甚至...
- 阿里云国际站:怎样计算内存优化型需求?
-
本文由【云老大】TG@yunlaoda360撰写一、内存优化型实例的核心价值内存优化型ECS实例专为数据密集型场景设计,具有以下核心优势:高内存配比:内存与CPU比例可达1:8(如ecs.re6....
- MySQL大数据量处理常用解决方案
-
1、读写分离读写分离,将数据库的读写操作分开,比如让性能比较好的服务器去做写操作,性能一般的服务器做读操作。写入或更新操作频繁可以借助MQ,进行顺序写入或更新。2、分库分表分库分表是最常规有效的一种大...
- 1024程序员节 花了三个小时调试 集合近50种常用小工具 开源项目
-
开篇1024是程序员节了,本来我说看个开源项目花半个小时调试之前看的一个不错的开源项目,一个日常开发常常使用的工具集,结果花了我三个小时,开源作者的开源项目中缺少一些文件,我一个个在网上找的,好多坑...
- 免费全开源,功能强大的多连接数据库管理工具!-DbGate
-
DBGate是一个强大且易于使用的开源数据库管理工具,它提供了一个统一的Web界面,让你能够轻松地访问和管理多种类型的数据库。无论你是开发者、数据分析师还是DBA,DBGate都能帮助你提升工作效率...
- 使用operator部署Prometheus
-
一、介绍Operator是CoreOS公司开发,用于扩展kubernetesAPI或特定应用程序的控制器,它用来创建、配置、管理复杂的有状态应用,例如数据库,监控系统。其中Prometheus-Op...
- java学习总结
-
SpringBoot简介https://spring.io/guideshttp://www.spring4all.com/article/246http://www.spring4all.com/a...
- Swoole难上手?从EasySwoole开始
-
前言有些童鞋感觉对Swoole不从下手,也不知在什么业务上使用它,看它这么火却学不会也是挺让人捉急的一件事情。Swoole:面向生产环境的PHP异步网络通信引擎啥是异步网络通信?10年架构师领你架...
- 一款商用品质的开源商城系统(Yii2+Vue2.0+uniapp)
-
一、项目简介这是一套很成熟的开源商城系统【开店星】,之前推过一次,后台感兴趣的还不少,今天再来详细介绍一下:基于Yii2+Vue2.0+uniapp框架研发,代码质量堪称商用品质,下载安装无门槛,UI...
- Yii2中对Composer的使用
-
如何理解Composer?若使用Composer我们应该先知道这是一个什么东西,主要干什么用的,我们可以把Composer理解为PHP包的管理工具,管理我们用到的Yii2相关的插件。安装Compose...
- SpringBoot实现OA自动化办公管理系统源码+代码讲解+开发文档
-
今天发布的是由【猿来入此】的优秀学员独立做的一个基于springboot脚手架的自动化OA办公管理系统,主要实现了日常办公的考勤签到等一些办公基本操作流程的全部功能,系统分普通员工、部门经理、管理员等...
- 7层架构解密:从UI到基础设施,打造真正可扩展的系统
-
"我们系统用户量暴增后完全崩溃了!"这是多少工程师的噩梦?选择正确的数据库只是冰山一角,真正的系统扩展性是一场全栈战役。客户端层:用户体验的第一道防线当用户点击你的应用时,0.1秒...
- Win11系统下使用Django+Celery异步任务队列以及定时(周期)任务
-
首先明确一点,celery4.1+的官方文档已经详细说明,该版本之后不需要引入依赖django-celery这个库了,直接用celery本身就可以了,就在去年年初的一篇文章python3.7....
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- oracle位图索引 (63)
- oracle批量插入数据 (62)
- oracle事务隔离级别 (53)
- oracle 空为0 (50)
- oracle主从同步 (55)
- oracle 乐观锁 (51)
- redis 命令 (78)
- php redis (88)
- redis 存储 (66)
- redis 锁 (69)
- 启动 redis (66)
- redis 时间 (56)
- redis 删除 (67)
- redis内存 (57)
- redis并发 (52)
- redis 主从 (69)
- redis 订阅 (51)
- redis 登录 (54)
- redis 面试 (58)
- 阿里 redis (59)
- redis 搭建 (53)
- redis的缓存 (55)
- lua redis (58)
- redis 连接池 (61)
- redis 限流 (51)