防止恶意刷接口、防止突发流量打崩服务、保护下游依赖。限流是系统稳定性的第一道闸。
| 算法 | 思路 | 特点 |
|---|---|---|
| 固定窗口 | 每秒最多 N 次 | 简单,但临界突刺 |
| 滑动窗口 | 滚动时间窗统计 | 更平滑,需计数存储 |
| 漏桶 | 固定速率流出 | 平滑突发,限速率 |
| 令牌桶 | 按速率放令牌,取令牌才放行 | 允许一定突发,最常用 |
-- Lua: 每毫秒补令牌,按桶容量限制
local key = KEYS[1]
local rate = tonumber(ARGV[1]) -- 每秒补充令牌数
local capacity = tonumber(ARGV[2]) -- 桶容量
local now = redis.call('TIME')[1]
local data = redis.call('HMGET', key, 'tokens', 'last')
local tokens = tonumber(data[1]) or capacity
local last = tonumber(data[2]) or now
tokens = math.min(capacity, tokens + (now - last) * rate)
if tokens < 1 then
return 0 -- 限流
end
redis.call('HMSET', key, 'tokens', tokens - 1, 'last', now)
redis.call('EXPIRE', key, 10)
return 1
from collections import deque, time
class SlidingWindow:
def __init__(self, limit, window):
self.limit = limit
self.window = window
self.hits = deque()
def allow(self):
now = time.time()
while self.hits and now - self.hits[0] >= self.window:
self.hits.popleft()
if len(self.hits) < self.limit:
self.hits.append(now)
return True
return False
分层:网关限流(全局)+ 应用限流(单实例)+ 熔断降级(保护下游),多层配合才稳。