如何基于 Redis 实现令牌桶?
解读
国内互联网高并发场景下,接口限流是面试必考点。令牌桶算法因支持“突发流量+匀速消费”被广泛使用,而 Redis 作为分布式高性能缓存天然适合跨节点共享令牌状态。面试官期望候选人能:
- 用 Redis 原子操作解决并发竞争;
- 结合 Spring 生态优雅落地;
- 考虑精度、性能、异常三大维度。
知识点
- 令牌桶核心参数:容量(capacity)、填充速率(rate)、上次填充时间(lastRefillTime)。
- Redis 原子命令:Lua 脚本保证“读-改-写”原子性;RedisTemplate 与 StringRedisTemplate 在 Spring 中的线程安全写法。
- 时间精度:Redis 服务器时钟与应用时钟可能不一致,需统一用 Redis 时间(
TIME命令)。 - 集群问题:Redisson 已内置
RRateLimiter,但面试官常问“不用 Redisson 如何手写”。 - Spring 集成:利用
@PostConstruct初始化桶,用 AOP 拦截@RateLimit注解,实现业务无侵入。
答案
步骤一:设计 Redis 数据结构
key=rate_limit:{resource},field 分别存剩余令牌数(tokens) 与上次填充毫秒时间戳(last_refill_ts)。
步骤二:Lua 脚本原子化
-- 参数:KEYS[1]=key, ARGV[1]=capacity, ARGV[2]=rate (每秒生成数), ARGV[3]=requested, ARGV[4]=nowMs
local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local rate = tonumber(ARGV[2])
local requested = tonumber(ARGV[3])
local now = tonumber(ARGV[4])
local tokens = redis.call('HMGET', key, 'tokens', 'last_refill_ts')
local left = tonumber(tokens[1]) or capacity
local last = tonumber(tokens[2]) or now
local delta = math.max(0, now - last)
local filled = math.min(capacity, left + delta * rate / 1000)
local allowed = 0
if filled >= requested then
allowed = 1
filled = filled - requested
end
redis.call('HMSET', key, 'tokens', filled, 'last_refill_ts', now)
redis.call('PEXPIRE', key, 3600000) -- 1h 过期,防脏数据
return allowed
步骤三:Spring 侧封装
@Component
public class RedisTokenBucket {
@Resource
private StringRedisTemplate rt;
private static final String SCRIPT =
// 上述 Lua 脚本内容,这里省略重复
public boolean tryAcquire(String resource, int capacity, int ratePerSecond, int requested) {
Long now = rt.execute((RedisConnection conn) ->
conn.time()); // 取 Redis 时间,避免时钟漂移
return rt.execute(
new DefaultRedisScript<>(SCRIPT, Long.class),
Collections.singletonList("rate_limit:" + resource),
String.valueOf(capacity),
String.valueOf(ratePerSecond),
String.valueOf(requested),
String.valueOf(now)
) == 1L;
}
}
步骤四:AOP 使用
@Aspect
@Component
public class RateLimitAspect {
@Autowired
private RedisTokenBucket bucket;
@Around("@annotation(rateLimit)")
public Object limit(ProceedingJoinPoint pjp, RateLimit rateLimit) throws Throwable {
boolean ok = bucket.tryAcquire(
rateLimit.resource(),
rateLimit.capacity(),
rateLimit.rate(),
1
);
if (!ok) throw new BizException("请求过于频繁,请稍后再试");
return pjp.proceed();
}
}
步骤五:压测调优
- QPS 1w+ 时,Lua 脚本 RTT 约 0.4ms,CPU 占用低于 5%;
- 若跨机房延迟高,可本地预取令牌+异步批量回写,但牺牲一定精度;
- 监控:把
allowed=0次数写入 Micrometer,对接 Prometheus+Grafana。
拓展思考
- 双桶策略:再引入漏桶做兜底,实现“突发吸收+匀速流出”,适用于支付下单场景。
- 动态速率:结合 Nacos 配置中心,热更新
rate参数,无需重启应用。 - 多维度限流:把用户 ID、IP、接口三维组合到 key 中,实现细粒度控制;注意key 数量爆炸时用 Redis Hash 分片。
- Redis 故障降级:主节点宕机时,脚本会抛
RedisSystemException,可切换至本地令牌桶(Guava RateLimiter)并告警,保证可用性优于一致性。