分布式自定义限流方案(基于 Redis + 注解)
下面是一套在分布式环境下可用的"注解限流"实现,核心特点:
- 使用
@RateLimit注解到方法上 - 通过 Spring AOP 拦截
- 限流规则存到 Redis,所有实例共享
- 使用 Lua 脚本保证原子性
- 支持按接口(默认)、自定义 key、IP 维度
记得点赞加收藏哦😁😁😁
1. 注解定义
java
package com.example.limiter.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimit {
/**
* 限流的时间窗口,单位:秒
* 比如 60 就是 60 秒内最多 N 次
*/
int windowSeconds() default 60;
/**
* 时间窗口内允许的最大访问次数
*/
int maxCount() default 100;
/**
* 限流的 key,默认空表示自动生成(类名#方法名)
* 可以写上 "#ip" 表示按 IP 限流(在切面里处理)
*/
String key() default "";
/**
* 是否按 IP 维度限流
*/
boolean perIp() default false;
}
2. Redis 限流服务
使用 Lua 做"滑动窗口/固定窗口计数"都行,这里给一个简单固定窗口计数版:key = prefix + windowStart,在窗口期内自增,超过就限。
Lua 脚本:
lua
-- KEYS[1] 限流key
-- ARGV[1] 窗口过期时间(秒)
-- ARGV[2] 最大次数
local current = redis.call("INCR", KEYS[1])
if tonumber(current) == 1 then
redis.call("EXPIRE", KEYS[1], tonumber(ARGV[1]))
end
if tonumber(current) > tonumber(ARGV[2]) then
return 0
end
return 1
Java 封装:
java
package com.example.limiter.core;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import java.util.Collections;
@Component
public class RedisRateLimiter {
private static final String SCRIPT =
"local current = redis.call('INCR', KEYS[1]) " +
"if tonumber(current) == 1 then " +
" redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1])) " +
"end " +
"if tonumber(current) > tonumber(ARGV[2]) then " +
" return 0 " +
"end " +
"return 1 ";
private final StringRedisTemplate stringRedisTemplate;
private final DefaultRedisScript<Long> redisScript;
public RedisRateLimiter(StringRedisTemplate stringRedisTemplate) {
this.stringRedisTemplate = stringRedisTemplate;
this.redisScript = new DefaultRedisScript<>();
this.redisScript.setScriptText(SCRIPT);
this.redisScript.setResultType(Long.class);
}
/**
* @param key redis限流key
* @param windowSeconds 窗口秒数
* @param maxCount 窗口内最大次数
* @return true 表示允许
*/
public boolean allowRequest(String key, int windowSeconds, int maxCount) {
Long res = stringRedisTemplate.execute(
redisScript,
Collections.singletonList(key),
String.valueOf(windowSeconds),
String.valueOf(maxCount)
);
return res != null && res == 1L;
}
}
3. AOP 切面
java
package com.example.limiter.aop;
import com.example.limiter.annotation.RateLimit;
import com.example.limiter.core.RedisRateLimiter;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.lang.reflect.Method;
@Aspect
@Component
public class RateLimitAspect {
private final RedisRateLimiter redisRateLimiter;
public RateLimitAspect(RedisRateLimiter redisRateLimiter) {
this.redisRateLimiter = redisRateLimiter;
}
@Before("@annotation(com.example.limiter.annotation.RateLimit)")
public void doBefore(JoinPoint joinPoint) {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
RateLimit rateLimit = method.getAnnotation(RateLimit.class);
String baseKey = rateLimit.key();
if (baseKey == null || baseKey.isEmpty()) {
// 默认用 类名#方法名
baseKey = joinPoint.getTarget().getClass().getName() + "#" + method.getName();
}
// 是否按IP限流
if (rateLimit.perIp()) {
HttpServletRequest request = currentRequest();
if (request != null) {
String ip = getClientIp(request);
baseKey = baseKey + ":ip:" + ip;
}
}
// 拼上时间窗口粒度可以更细,但这里用脚本里的expire就够了
boolean allowed = redisRateLimiter.allowRequest(
"rate:limit:" + baseKey,
rateLimit.windowSeconds(),
rateLimit.maxCount()
);
if (!allowed) {
// 超过阈值,抛异常或返回特定错误
throw new RuntimeException("Too many requests, please try later.");
}
}
private HttpServletRequest currentRequest() {
ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
return attrs == null ? null : attrs.getRequest();
}
private String getClientIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
// 多级代理取第一个
return ip.split(",")[0];
}
ip = request.getHeader("X-Real-IP");
if (ip != null && !ip.isEmpty() && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
return request.getRemoteAddr();
}
}
4. Controller 使用示例
java
import com.example.limiter.annotation.RateLimit;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DemoController {
// 60秒内最多10次
@RateLimit(windowSeconds = 60, maxCount = 10)
@GetMapping("/demo")
public String demo() {
return "ok";
}
// 针对IP限流
@RateLimit(windowSeconds = 60, maxCount = 5, perIp = true)
@GetMapping("/ip-demo")
public String ipDemo() {
return "ok";
}
// 自定义key(比如按业务维度)
@RateLimit(windowSeconds = 10, maxCount = 3, key = "sendSms")
@GetMapping("/send-sms")
public String sms() {
return "sms ok";
}
}
5. 依赖说明
需要 Spring Data Redis:
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application.yml 至少得有:
yaml
spring:
data:
redis:
host: localhost
port: 6379
6. 思路扩展
- 滑动窗口:现在是固定窗口计数,足够大部分接口。如果想更平滑,可以把 Lua 换成 zset 写法。
- 返回码:上面直接抛 RuntimeException,你可以换成自定义业务异常,ControllerAdvice 统一返回 429。
- 多规则 :可以在注解里加枚举,比如
type=LIMIT_IP、LIMIT_USER,切面里不同拼 key 即可。 - 限流配置中心:如果你不想写死注解里的值,可以在切面里先查一把 Redis/DB 的限流配置,查不到再用注解默认值。
这样这一套就是分布式可用的注解限流 了,核心就是:所有实例都去 Redis 抢同一个 key 的次数,再加 Lua 保证自增+过期是原子的。