在分布式系统设计中,限流是保障服务稳定性的核心技术之一。滑动窗口限流算法以其精确性和平滑性优势,成为解决传统固定窗口限流临界突变问题的理想方案。本文将深入解析滑动窗口算法原理,并通过aop+redis滑动窗口限流。
固定窗口与滑动窗口对比
固定窗口限流及其缺陷
固定窗口限流将时间划分为固定区间(如每分钟),统计每个区间内的请求数量。这种方法虽然简单,但存在严重缺陷:

当大量请求集中在两个窗口的交界处时(如00:59:59和01:00:00),系统会在极短时间内接收双倍于阈值的请求,导致服务过载。滑动窗口限流通过动态时间区间解决了这个问题。
核心原理:为每个请求动态定义一个以当前时间为终点、向前回溯固定时长t的时间区间(滑动窗口),统计该区间内的请求数:
- 动态窗口:每个请求到达时计算
[当前时间 - t, 当前时间]区间 - 实时统计:计算该区间内的请求数量
- 决策执行:请求数 < 阈值 → 允许;否则拒绝
- 窗口滑动:过期请求自动移出统计范围
redis实现方案
redis的有序集合(zset)是实现滑动窗口限流的理想数据结构:
zset结合了集合(set)和哈希(hash)的特性:
- 唯一成员:每个成员(member)在集合中唯一
- 分数排序:每个成员关联一个分数(score),用于排序
- 自动排序:成员按分数值从小到大排序
之所以是滑动窗口限流的理想选择,关键在于它完美解决了滑动窗口算法的三个核心需求:
- 时间序列的天然支持:zset的分数(score)机制为时间戳提供了原生支持。当我们将请求时间戳作为score存储时,所有请求按时间顺序自动排序,形成精确的时间序列。这使得界定时间窗口边界变得简单——只需计算
当前时间 - 窗口大小就能得到窗口起始点,无需额外维护时间索引。这种设计让滑动窗口的"滑动"机制得以自然实现。 - 高效的范围操作能力:滑动窗口的核心操作是清理过期请求,zset的
zremrangebyscore命令正是为此而生。它能以o(log(n)+m)的复杂度高效删除指定时间范围外的历史请求。这种高效的范围删除能力确保了窗口滑动时的实时性能。 - 精确的实时统计特性:通过
zcard和zcount命令,zset提供原子级的精确计数能力。在滑动窗口算法中,我们需要实时统计当前窗口内的请求数并与阈值比较,这些命令能以o(1)和o(log(n))复杂度瞬间完成统计。这种即时反馈机制对高并发场景至关重要,确保限流决策的及时性和准确性。
| 命令 | 统计范围 | 时间复杂度 | 典型使用场景 |
|---|---|---|---|
| zcard key | 整个 zset 的总成员数 | o(1) | 清理过期数据后快速获取当前窗口请求总数 |
| zcount key min max | 指定 score 范围内的成员数 | o(log(n)) | 动态统计子窗口/特定时间段的请求量 |
代码
自定义注解
首先自定义注解,定义限流维度、窗口大小、时间单位、窗口内最大请求数量
@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface slidingwindowlimit {
/**
* 限流维度的 spel 表达式
* 示例:
* - 按邮箱: "#email"
* - 按 ip: "#request.remoteaddr"
* - 按用户 id + 邮箱: "#user.id + ':' + #user.email"
*/
string keyspel() default "#email";
/**
* 窗口大小
*/
int windowsize() default 60;
/**
* 时间单位
*/
timeunit timeunit() default timeunit.seconds;
/**
* 窗口内最大请求数
*/
int maxrequests() default 10;
}

切面类
1. 切面配置与基础结构
首先创建切面类
@aspect
@component
@order(ordered.highest_precedence + 20)
public class slidingwindowlimitaspect {
@resource
private redissonclient redissonclient;
private static final logger log = loggerfactory.getlogger(slidingwindowlimitaspect.class);
private static final string rate_limit_prefix = "rate_limit";
}
@aspect:声明该类为aop切面@order:设置切面执行优先级(数字越小优先级越高)redissonclient:redis客户端操作接口rate_limit_prefix:redis键名前缀,用于区分限流数据
2. 切面入口方法 - around()
@around("@annotation(slidingwindowlimit)")
public object around(proceedingjoinpoint joinpoint, slidingwindowlimit slidingwindowlimit) throws throwable {
//获取方法签名
methodsignature signature = (methodsignature) joinpoint.getsignature();
method method = signature.getmethod();
string methodname = method.getname();
//判断是否为http请求
servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.getrequestattributes();
if(attributes == null){
log.warn("方法 {} 不在 web 请求上下文中,跳过限流检查。", methodname);
return joinpoint.proceed();
}
try {
object parsespel = parsespel(joinpoint, signature, slidingwindowlimit.keyspel());
string ratelimitkey = buildratelimitkey(parsespel, slidingwindowlimit);
if(isratelimited(ratelimitkey, slidingwindowlimit.windowsize(), slidingwindowlimit.timeunit(), slidingwindowlimit.maxrequests())){
throw new ratelimitexceededexception("rate limit exceeded");
}
return joinpoint.proceed();
}catch (ratelimitexceededexception e){
log.warn("方法 {} 触发了限流,已拒绝访问。", methodname);
throw e;
}catch (exception e){
log.error("方法 {} 触发了异常,已拒绝访问。", methodname, e);
throw e;
}
}
执行过程:

3. spel解析方法 - parsespel()
private object parsespel(proceedingjoinpoint joinpoint,methodsignature signature, string keyspel){
standardevaluationcontext context = new standardevaluationcontext();
object[] args = joinpoint.getargs();
string[] parameternames = signature.getparameternames();
for (int i = 0; i < args.length; i++) {
if(parameternames!=null && i< parameternames.length){
context.setvariable(parameternames[i], args[i]);
}else {
context.setvariable("arg" + i, args[i]);
}
}
expressionparser parser = new spelexpressionparser();
return parser.parseexpression(keyspel).getvalue(context);
}
功能说明:
- 动态解析注解中的spel表达式(如
#email) - 将方法参数注入表达式上下文
- 支持灵活的限流键生成策略
4.限流键构建方法 - buildratelimitkey()
private string buildratelimitkey(object keyvalue, slidingwindowlimit slidingwindowlimit){
if(keyvalue == null){
throw new illegalargumentexception("限流参数不能为空");
}
return string.format("%s:%s:%s",rate_limit_prefix,slidingwindowlimit.keyspel(), keyvalue);
}
键格式说明:
rate_limit:spel表达式:参数值 ↓ ↓ ↓ rate_limit:#email:user@example.com
5. 限流核心逻辑 - isratelimited()
private boolean isratelimited(string key, int windowsize, timeunit timeunit, int maxrequests){
//获取当前时间数
long currenttime = system.currenttimemillis();
long windowstarttime = currenttime - converttomillis(windowsize, timeunit);
// 获取 redisson 的 zset 操作对象
rscoredsortedset<long> scoredsortedset = redissonclient.getscoredsortedset(key);
// 1. 删除窗口外的过期请求
scoredsortedset.removerangebyscore(0, true, windowstarttime, true); // [0, windowstarttime]
// 2. 添加当前请求的时间戳到 zset
scoredsortedset.add(currenttime, currenttime); // score 和 value 均为时间戳
// 3. 统计窗口内请求数量
int count = scoredsortedset.size();
return count > maxrequests;
}
redis操作序列:
zremrangebyscore key 0 windowstart:删除过期请求zadd key currenttime currenttime:添加当前请求zcard key:获取当前请求数
6. 时间单位转换 - converttomillis()
private long converttomillis(int windowsize, timeunit timeunit) {
return switch (timeunit) {
case seconds -> timeunit.tomillis(windowsize);
case minutes -> timeunit.tomillis(windowsize);
case hours -> timeunit.tomillis(windowsize);
case days -> timeunit.tomillis(windowsize);
case milliseconds -> windowsize;
default -> throw new illegalargumentexception("不支持的时间单位: " + timeunit);
};
}
完整代码
@aspect
@component
@order(ordered.highest_precedence + 20)
public class slidingwindowlimitaspect {
@resource
private redissonclient redissonclient;
private static final logger log = loggerfactory.getlogger(slidingwindowlimitaspect.class);
private static final string rate_limit_prefix = "rate_limit";
@around("@annotation(slidingwindowlimit)")
public object around(proceedingjoinpoint joinpoint, slidingwindowlimit slidingwindowlimit) throws throwable {
//获取方法签名
methodsignature signature = (methodsignature) joinpoint.getsignature();
method method = signature.getmethod();
string methodname = method.getname();
//判断是否为http请求
servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.getrequestattributes();
if(attributes == null){
log.warn("方法 {} 不在 web 请求上下文中,跳过限流检查。", methodname);
return joinpoint.proceed();
}
try {
object parsespel = parsespel(joinpoint, signature, slidingwindowlimit.keyspel());
string ratelimitkey = buildratelimitkey(parsespel, slidingwindowlimit);
if(isratelimited(ratelimitkey, slidingwindowlimit.windowsize(), slidingwindowlimit.timeunit(), slidingwindowlimit.maxrequests())){
throw new ratelimitexceededexception("rate limit exceeded");
}
return joinpoint.proceed();
}catch (ratelimitexceededexception e){
log.warn("方法 {} 触发了限流,已拒绝访问。", methodname);
throw e;
}catch (exception e){
log.error("方法 {} 触发了异常,已拒绝访问。", methodname, e);
throw e;
}
}
private object parsespel(proceedingjoinpoint joinpoint,methodsignature signature, string keyspel){
standardevaluationcontext context = new standardevaluationcontext();
object[] args = joinpoint.getargs();
string[] parameternames = signature.getparameternames();
for (int i = 0; i < args.length; i++) {
if(parameternames!=null && i< parameternames.length){
context.setvariable(parameternames[i], args[i]);
}else {
context.setvariable("arg" + i, args[i]);
}
}
expressionparser parser = new spelexpressionparser();
return parser.parseexpression(keyspel).getvalue(context);
}
private string buildratelimitkey(object keyvalue, slidingwindowlimit slidingwindowlimit){
if(keyvalue == null){
throw new illegalargumentexception("限流参数不能为空");
}
return string.format("%s:%s:%s",rate_limit_prefix,slidingwindowlimit.keyspel(), keyvalue);
}
private boolean isratelimited(string key, int windowsize, timeunit timeunit, int maxrequests){
//获取当前时间数
long currenttime = system.currenttimemillis();
long windowstarttime = currenttime - converttomillis(windowsize, timeunit);
// 获取 redisson 的 zset 操作对象
rscoredsortedset<long> scoredsortedset = redissonclient.getscoredsortedset(key);
// 1. 删除窗口外的过期请求
scoredsortedset.removerangebyscore(0, true, windowstarttime, true); // [0, windowstarttime]
// 2. 添加当前请求的时间戳到 zset
scoredsortedset.add(currenttime, currenttime); // score 和 value 均为时间戳
// 3. 统计窗口内请求数量
int count = scoredsortedset.size();
return count > maxrequests;
}
/**
* 时间单位转换,将时间单位转换为毫秒数
* @param windowsize 窗口大小
* @param timeunit 时间单位
* @return
*/
private long converttomillis(int windowsize, timeunit timeunit){
return switch (timeunit){
case nanoseconds, seconds, microseconds, minutes, hours, days -> timeunit.tomillis(windowsize);
case milliseconds -> windowsize;
default -> throw new illegalargumentexception("不支持的时间单位: " + timeunit);
};
}
}
注解使用
比如说我们现在定义发送验证码的方法60秒内只能发送三次
@postmapping("/send/code")
@slidingwindowlimit(keyspel = "#email.email",windowsize = 60, maxrequests = 3)
public result sendverificationcode(@requestbody emailsenddto email) {
userservice.sendverificationcode(email.getemail());
return result.success();
}
每一次访问时,redis都会记录下时间戳,如果第四次访问时的时间戳与第一次访问的时间戳之间少于60秒,则返回
{
"code": 429,
"message": "请求过于频繁,请稍后再试",
"data": null
}
优化
private boolean isratelimited(string key, int windowsize, timeunit timeunit, int maxrequests){
//获取当前时间数
long currenttime = system.currenttimemillis();
long windowstarttime = currenttime - converttomillis(windowsize, timeunit);
// 获取 redisson 的 zset 操作对象
rscoredsortedset<long> scoredsortedset = redissonclient.getscoredsortedset(key);
// 1. 删除窗口外的过期请求
scoredsortedset.removerangebyscore(0, true, windowstarttime, true); // [0, windowstarttime]
// 2. 添加当前请求的时间戳到 zset
scoredsortedset.add(currenttime, currenttime); // score 和 value 均为时间戳
// 3. 统计窗口内请求数量
int count = scoredsortedset.size();
return count > maxrequests;
}
在这个方法中,存在几个问题:
代码中直接将时间戳作为zset的成员(member)和分数(score),当同一毫秒内有多个请求时,后写入的请求会覆盖先前的请求(zset成员唯一),导致计数不准确。
当前操作序列:
在并发场景下,多个请求可能同时通过计数检查,导致实际请求量超过阈值
- 删除过期请求
- 添加当前请求
- 获取当前计数
当某个限流键长时间无请求时,对应的空zset会永久占用内存
那么优化时,可以利用uuid作为member 这样不会出现覆盖的情况,使用lua脚本进行执行避免多个请求同时通过计数检查的情况,针对问题三可以通过设置过期时间来解决,优化后的代码如下:
private boolean isratelimited(string key, int windowsize, timeunit timeunit, int maxrequests) {
// 1. 计算窗口大小(毫秒)
long windowmillis = converttomillis(windowsize, timeunit);
// 2. 获取当前时间和窗口起始时间
long currenttime = system.currenttimemillis();
long windowstarttime = currenttime - windowmillis;
// 3. 生成唯一请求id
string requestid = uuid.randomuuid().tostring();
// 4. 计算过期时间(秒)
long expireseconds = calculateexpireseconds(windowmillis);
// 5. lua脚本(使用分数范围精确统计)
string luascript =
"redis.call('zremrangebyscore', keys[1], '-inf', argv[2])\n" + // 清理过期数据
"local count = redis.call('zcount', keys[1], argv[2], argv[1])\n" + // 精确统计窗口内请求
"if count >= tonumber(argv[4]) then\n" +
" return 1\n" + // 触发限流
"end\n" +
"redis.call('zadd', keys[1], argv[1], argv[3])\n" + // 添加当前请求
"redis.call('expire', keys[1], argv[5])\n" + // 设置过期时间
"return 0"; // 允许通过
try {
rscript script = redissonclient.getscript();
long result = script.eval(
rscript.mode.read_write,
luascript,
rscript.returntype.integer,
collections.singletonlist(key),
currenttime, windowstarttime, requestid, maxrequests, expireseconds
);
return result != null && result == 1;
} catch (exception e) {
log.error("限流服务异常,降级放行", e);
return false; // redis故障时允许请求
}
}
private long calculateexpireseconds(long windowmillis) {
// 过期时间 = 2 * 窗口大小(秒),向上取整
double expiresec = (windowmillis * 2.0) / 1000;
long result = (long) math.ceil(expiresec);
return math.max(1, result); // 至少1秒
}
lua 脚本执行逻辑:
redis.call('zremrangebyscore', keys[1], '-inf', argv[2]):清理过期数据,将 zset 中分数小于等于窗口起始时间的成员删除。local count = redis.call('zcount', keys[1], argv[2], argv[1]):精确统计窗口内请求数量,即分数在窗口起始时间和当前时间之间的成员数量。if count >= tonumber(argv[4]) then return 1 end:如果统计的请求数量大于等于阈值,则返回 1,表示触发限流。redis.call('zadd', keys[1], argv[1], argv[3]):添加当前请求,将当前请求的唯一 id 作为成员,当前时间作为分数添加到 zset 中。redis.call('expire', keys[1], argv[5]):设置 zset 的过期时间,避免长时间无请求时空 zset 占用内存。return 0:如果未触发限流,则返回 0,表示允许请求通过。
我们从命令行可以看到,每一次请求后,都会在zset中多一条记录,并且每次都会重置过期时间,当触发限流后,不再允许访问。
127.0.0.1:6379> zrange rate_limit:#email.email:6888@example.com 0 -1 1) "fbd525dd-0e1e-4abf-a578-8c1207e8f6f0" 127.0.0.1:6379> ttl rate_limit:#email.email:6888@example.com (integer) 355 127.0.0.1:6379> zrange rate_limit:#email.email:6888@example.com 0 -1 1) "fbd525dd-0e1e-4abf-a578-8c1207e8f6f0" 2) "a7c8d5c2-f4da-46ce-9f98-472ad702e1ad" 127.0.0.1:6379> ttl rate_limit:#email.email:6888@example.com (integer) 355 127.0.0.1:6379> zrange rate_limit:#email.email:6888@example.com 0 -1 1) "fbd525dd-0e1e-4abf-a578-8c1207e8f6f0" 2) "a7c8d5c2-f4da-46ce-9f98-472ad702e1ad" 3) "12ed502c-6225-45bd-b85e-1d3ed9e46ef6" 127.0.0.1:6379> ttl rate_limit:#email.email:6888@example.com (integer) 355

到此这篇关于基于aop+redis的简易滑动窗口限流的文章就介绍到这了,更多相关aop+redis滑动窗口限流内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论