滑动窗口解决分布式限流问题

一.引言

1.说明

技术分享型博客,面向Java后端开发者,需要一定lua脚本经验

目标:让读者理解滑动窗口限流原理、掌握常用实现方法、并能在实际项目中落地

为什么需要滑动窗口限流?

在高并发系统中,一个接口如果没有限流策略,可能会因为短时间内大量请求导致:

  • 系统资源耗尽(CPU/内存/数据库连接)
  • 服务崩溃或请求响应延迟大
  • 安全风险,例如暴力破解登录、刷接口

因此,我们需要一种机制控制单位时间内请求量。

2.常见的限流算法

常见算法有:

  1. 固定窗口计数
  2. 滑动窗口计数(Sliding Window)
  3. 漏桶(Leaky Bucket)
  4. 令牌桶(Token Bucket)

本文重点讲滑动窗口算法

3.滑动窗口限流算法原理

滑动窗口是一种时间窗口动态统计请求数的方法,核心思想是:

  • 统计最近 N 秒内 的请求数
  • 判断请求是否超过限流阈值

本文主要讲解Redis实现(分布式) 实现限流

  • 用 Sorted Set 存储请求时间戳
  • 命令:(后面会重点讲解)
    1. ZADD key timestamp timestamp → 添加请求
    2. ZREMRANGEBYSCORE key 0 (now - window) → 删除过期请求
    3. ZCARD key → 获取当前请求数
    4. 小于阈值 → 允许请求,否则拒绝

优点:支持分布式、多实例共享计数

二.滑动窗口限流的实现

1.Lua脚本实现滑动窗口

​ lua脚本是一个可以绕开服务器,直接对redis、数据库直接进行操作数据的脚本。这样可以提高并发量,减少服务器的压力。是许多游戏脚本的实现手段。常有名言:

​ 师傅领进门,判刑看个人 ^o^

​ 这篇文章的lua脚本是直接操作redis缓存,在redis进行限流,返回是否能狗请求

​ 该lua脚本存放位置 :iam-service\src\main\resources\lua\sms_rate_limit.lua

​ lua脚本设计思路:

[[
短信限流 Lua 脚本(滑动窗口,多层频控 + 用户分级)
从多个维度(电话、username)对用户进行分级

这是由后端传入的key——对应redis的key
KEYS:
KEYS[1] - 手机维度 ZSET key,例如 iam:auth:sms:win:phone:{phone}
KEYS[2] - 用户维度 ZSET key,例如 iam:auth:sms:win:user:{username}
#这是参数
ARGV:
ARGV[1] - 当前时间戳(毫秒)
ARGV[2] - 用户等级:NORMAL / VIP / RISKY

返回:
{ allowedFlag, waitSeconds }
- allowedFlag = 1 允许本次发送,并已记录到各维度窗口
- allowedFlag = 0 拒绝本次发送,waitSeconds 为最大剩余等待时间(秒)
]]

​ 脚本的实现

# 由后端传入
local now = tonumber(ARGV[1])
local grade = ARGV[2]

# 定义各个用户等级的限流规则
# 根据用户的等级有不同的规则
# NORMAL 正常
# VIP
# RISKY 危险
# 结构:rules[grade][dimension] = { {windowMillis, maxCount}, ... }
local rules = {}

rules["NORMAL"] = {
phone = {
{60000, 1}, # 60s 内最多 1 条
{600000, 3}, # 10min 内最多 3 条
{3600000, 6}, # 1h 内最多 6 条
{86400000, 20} # 24h 内最多 20 条
},
user = {
{600000, 5}, # 10min 内最多 5 条
{3600000, 10}, # 1h 内最多 10 条
{86400000, 30} # 24h 内最多 30 条
}
}

rules["VIP"] = {
phone = {
{60000, 2}, # 60s 内最多 2 条
{600000, 5}, # 10min 内最多 5 条
{3600000, 10}, # 1h 内最多 10 条
{86400000, 40} # 24h 内最多 40 条
},
user = {
{600000, 10}, # 10min 内最多 10 条
{3600000, 20}, # 1h 内最多 20 条
{86400000, 60} # 24h 内最多 60 条
}
}

rules["RISKY"] = {
phone = {
{60000, 1}, # 60s 内最多 1 条
{600000, 2}, # 10min 内最多 2 条
{3600000, 3}, # 1h 内最多 3 条
{86400000, 5} # 24h 内最多 5 条
},
user = {
{600000, 3}, # 10min 内最多 3 条
{3600000, 5}, # 1h 内最多 5 条
{86400000, 10} # 24h 内最多 10 条
}
}

# 默认使用 NORMAL 配置
local conf = rules[grade]
if conf == nil then
conf = rules["NORMAL"]
end

# 计算最长窗口,用于设置 key 的过期时间
local function maxWindowMillisForDimension(dimRules)
local maxWindow = 0
for i, rule in ipairs(dimRules) do
local window = rule[1]
# 获取所有窗口的存在最长时间
if window > maxWindow then
maxWindow = window
end
end
return maxWindow
end

local maxWindowMillis = 0
for _, dimRules in pairs(conf) do
local dMax = maxWindowMillisForDimension(dimRules)
if dMax > maxWindowMillis then
maxWindowMillis = dMax
end
end

# 针对单个维度执行滑动窗口检查
# 返回:allowedFlag(0/1), waitSeconds
local function checkDimension(key, dimRules)
if key == nil or key == '' or dimRules == nil then
return 1, 0
end

local dimMaxWait = 0

for i, rule in ipairs(dimRules) do
# 获取窗口时间范围
local windowMillis = rule[1]
# 窗口允许的最大请求量
local maxCount = rule[2]
# 计算当前窗口的时间
local start = now - windowMillis

# 清理窗口外的数据
# ZREMRANGEBYSCORE key min max
# 删除 ZSET 中 score 在 [min, max] 范围内的所有成员
# 返回值:删除的成员数量
redis.call("ZREMRANGEBYSCORE", key, 0, start)
# 获取当前用户在窗口期内的请求数量
local count = redis.call("ZCARD", key)
# 假如超过了允许请求量
if count >= maxCount then
# 获取窗口内最早的一条记录用于计算等待时间
local oldest = redis.call("ZRANGE", key, 0, 0, "WITHSCORES")
if oldest ~= nil and #oldest > 0 then
local oldestScore = tonumber(oldest[2])
# 计算需要返回的等待时间
local waitMillis = oldestScore + windowMillis - now
if waitMillis > 0 then
local waitSeconds = math.floor((waitMillis + 999) / 1000)
if waitSeconds > dimMaxWait then
dimMaxWait = waitSeconds
end
end
end
end
end

if dimMaxWait > 0 then
return 0, dimMaxWait
else
return 1, 0
end
end

# 从后端获取数据
local phoneKey = KEYS[1]
local userKey = KEYS[2]

# 调用滑动窗口限流函数
local phoneAllowed, phoneWait = checkDimension(phoneKey, conf["phone"])
local userAllowed, userWait = checkDimension(userKey, conf["user"])

# 如有任一维度不允许,则整体不允许,返回最大等待时间
if phoneAllowed == 0 or userAllowed == 0 then
local maxWait = phoneWait
if userWait > maxWait then
maxWait = userWait
end
return {0, maxWait}
end

# 所有维度均允许时,写入当前记录,并设置合理的过期时间
if phoneKey ~= nil and phoneKey ~= '' then
redis.call("ZADD", phoneKey, now, now)
if maxWindowMillis > 0 then
# 用于设置过期时间
local ttlSeconds = math.floor((maxWindowMillis * 2) / 1000)
redis.call("EXPIRE", phoneKey, ttlSeconds)
end
end

if userKey ~= nil and userKey ~= '' then
redis.call("ZADD", userKey, now, now)
if maxWindowMillis > 0 then
local ttlSeconds = math.floor((maxWindowMillis * 2) / 1000)
redis.call("EXPIRE", userKey, ttlSeconds)
end
end

return {1, 0}

2.在后端引入lua脚本

我们都lua脚本不是直接写在程序里面的,需要通过springboot引入。

相当于将脚本的功能抽象成一个bean,存放在spring容器里

@Configuration
public class SmsRateLimitConfiguration {
/**
* 基于滑动窗口算法的短信限流脚本。
*
* @return Redis 脚本 Bean,返回值为 List:
* [0] - allowedFlag (Long),1 表示允许,0 表示拒绝
* [1] - waitSeconds (Long),拒绝时的剩余等待时间
*/
@Bean
public DefaultRedisScript<List> smsRateLimitScript() {
/*相当于将脚本的功能抽象成一个bean,存放在spring容器里*/
DefaultRedisScript<List> script = new DefaultRedisScript<>();
/*存放路径*/
script.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/sms_rate_limit.lua")));
script.setResultType(List.class);
return script;
}
}

3.创建返回类型

/**
* 短信限流结果
*
* 用于承载 Lua 脚本返回的限流判断结果:
* - allowed: 是否允许本次发送
* - waitSeconds: 如果不允许,需要等待的秒数
*/
public class SmsRateLimitResult {

private final boolean allowed;
private final long waitSeconds;

public SmsRateLimitResult(boolean allowed, long waitSeconds) {
this.allowed = allowed;
this.waitSeconds = waitSeconds;
}

public boolean isAllowed() {
return allowed;
}

public long getWaitSeconds() {
return waitSeconds;
}
}

4.创建SmsRateLimitService

这个SmsRateLimitService的功能就是调用该脚本

@Service
public class SmsRateLimitService {

private static final Logger log = LoggerFactory.getLogger(SmsRateLimitService.class);
/*存放在redis中的用户信息——电话和username*/
private static final String PHONE_RATE_KEY_PREFIX = "iam:auth:sms:win:phone:";
private static final String USER_RATE_KEY_PREFIX = "iam:auth:sms:win:user:";

private final StringRedisTemplate redisTemplate;
/*引入"脚本对象"*/
private final DefaultRedisScript<List> smsRateLimitScript;

public SmsRateLimitService(StringRedisTemplate redisTemplate,
DefaultRedisScript<List> smsRateLimitScript) {
this.redisTemplate = redisTemplate;
this.smsRateLimitScript = smsRateLimitScript;
}

/**
* 执行短信发送前的限流检查
*
* @param user 当前账号
* @param phone 手机号
* @return 限流结果:allowed / waitSeconds
*/
public SmsRateLimitResult checkAndConsume(IamUser user, String phone) {
/*获取对象的等级权限,作为脚本参数*/
String grade = resolveGrade(user);
long now = System.currentTimeMillis();

List<String> keys = new ArrayList<>();
/*lua脚本参数*/
keys.add(PHONE_RATE_KEY_PREFIX + phone);
keys.add(USER_RATE_KEY_PREFIX + user.getUsername());
/*lua脚本参数*/
List<String> args = Arrays.asList(String.valueOf(now), grade);

try {
/*执行lua脚本的位置,将参数传入,redis会执行该脚本,返回结果*/
List result = redisTemplate.execute(smsRateLimitScript, keys, args.toArray());
if (result == null || result.size() < 2) {
/*Redis 脚本执行异常或未返回预期结果时,默认放行,避免影响登录主链路*/
log.warn("smsRateLimitScript returned unexpected result: {}", result);
return new SmsRateLimitResult(true, 0L);
}
Object allowedFlag = result.get(0);
Object waitSeconds = result.get(1);

boolean allowed = true;
long wait = 0L;

/*判断allowedFlag是否为数字类型*/
if (allowedFlag instanceof Number) {
allowed = ((Number) allowedFlag).longValue() == 1L;
}
if (waitSeconds instanceof Number) {
wait = ((Number) waitSeconds).longValue();
}

return new SmsRateLimitResult(allowed, wait);
} catch (DataAccessException ex) {
/*Redis 异常时不阻断登录,仅记录日志,用于排查*/
log.error("Failed to execute smsRateLimitScript", ex);
return new SmsRateLimitResult(true, 0L);
}
}

/**
* 用户分级:
* - 包含 ADMIN / OP / VIP 角色的账号视为 VIP
* - 如后续增加风险识别,可以在此扩展返回 RISKY
* - 其他账号默认为 NORMAL
*/
private String resolveGrade(IamUser user) {
String roles = user.getRoles();
if (roles != null) {
if (roles.contains("ADMIN") || roles.contains("OP") || roles.contains("VIP")) {
return "VIP";
}
}
/*预留:结合风控结果返回 "RISKY"*/
return "NORMAL";
}
}

5.调用SmsRateLimitService

SmsRateLimitResult rateLimitResult = smsRateLimitService.checkAndConsume(user, phone);
/*根据脚本执行结果,向前端发送信息*/
if (!rateLimitResult.isAllowed()) {
long waitSeconds = rateLimitResult.getWaitSeconds();
String message = "请求频次过高,请 " + waitSeconds + " 秒后再试";
throw new BusinessException(ErrorCode.TOO_MANY_REQUESTS, message);
}

至此,滑动窗口实现实现限流功能讲解完毕!