发布于2026-07-24 阅读(0)
扫一扫,手机访问
限流,说白了就是后端防护的第一道闸门。用 AOP 配合 Redis,搞一个自定义注解,往接口上一贴就能生效——这件事听起来简单,但真要落地,其实有不少细节。下面就把这套方案拆开揉碎了讲清楚。

先定义注解的属性。这里需要明确几个字段:限流的 key、维度(按用户/按 IP/按接口)、窗口内最大请求数、窗口大小,以及被限流后的提示信息。这样设计,后续扩展起来也方便。
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {
/** 限流 key */
String key() default "";
/** 限流维度:user / ip / api */
String type() default "user";
/** 窗口内最大请求数 */
long max() default 10;
/** 窗口大小(秒) */
long window() default 1;
/** 被限后的提示 */
String message() default "请求太频繁,请稍后重试";
}
注解定义好了,接下来就是核心的逻辑处理。用 AOP 拦截所有加了 @RateLimit 的方法,然后通过 Redis 的有序集合(ZSet)做滑动窗口限流。这里的关键是 Lua 脚本保证原子性,避免并发场景下计数不准。
@Aspect
@Component
public class RateLimitAspect {
@Autowired
private StringRedisTemplate redisTemplate;
@Around("@annotation(rateLimit)")
public Object around(ProceedingJoinPoint pjp, RateLimit rateLimit) throws Throwable {
String key = buildKey(rateLimit);
// 滑动窗口限流
boolean allowed = tryAcquire(key, rateLimit.max(), rateLimit.window());
if (!allowed) {
throw new BusinessException(429, rateLimit.message());
}
return pjp.proceed();
}
private boolean tryAcquire(String key, long max, long windowSec) {
long now = System.currentTimeMillis();
long windowMs = windowSec * 1000L;
long windowStart = now - windowMs;
// Lua 脚本保证原子性
String lua =
"redis.call('ZREMRANGEBYSCORE', KEYS[1], 0, ARGV[1]) " +
"local count = redis.call('ZCARD', KEYS[1]) " +
"if count < tonumber(ARGV[2]) then " +
" redis.call('ZADD', KEYS[1], ARGV[3], ARGV[3]) " +
" redis.call('EXPIRE', KEYS[1], ARGV[4]) " +
" return 1 " +
"else " +
" return 0 " +
"end";
Long result = redisTemplate.execute(
new DefaultRedisScript<>(lua, Long.class),
Collections.singletonList(key),
String.valueOf(windowStart),
String.valueOf(max),
String.valueOf(now),
String.valueOf(windowSec + 1)
);
return Long.valueOf(1).equals(result);
}
private String buildKey(RateLimit rateLimit) {
String prefix = "rate:";
switch (rateLimit.type()) {
case "ip":
HttpServletRequest request = ((ServletRequestAttributes)
RequestContextHolder.getRequestAttributes()).getRequest();
return prefix + "ip:" + getIp(request);
case "api":
return prefix + "api:" + Stream.of(
Thread.currentThread().getStackTrace())
.filter(s -> s.getMethodName().contains("$"))
.findFirst().orElse(new StackTraceElement("", "", "", 0))
.getMethodName();
default:
// type = user
return prefix + "user:" + StpUtil.getLoginIdAsString();
}
}
public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.isEmpty()) ip = request.getHeader("X-Real-IP");
if (ip == null || ip.isEmpty()) ip = request.getRemoteAddr();
if (ip != null && ip.contains(",")) ip = ip.split(",")[0].trim();
return ip;
}
}
使用方式很直接:在 Controller 的方法上加上 @RateLimit 注解,指定好限流维度和参数即可。比如对某个 GET 接口限制每个 IP 在 10 秒内最多 5 次请求,或者对秒杀接口限制每个用户 10 秒内只能请求 1 次。
@RestController
@RequestMapping("/api")
public class TestController {
@GetMapping("/test")
@RateLimit(key = "test", type = "ip", max = 5, window = 10)
public ResultVO> test() {
return ResultVO.success("成功");
}
@PostMapping("/seckill/{productId}")
@RateLimit(type = "user", max = 1, window = 10)
public ResultVO> seckill(@PathVariable Long productId) {
return ResultVO.success("秒杀成功");
}
}
被限流之后,切面会抛出 BusinessException,所以需要一个全局异常处理器来捕获,并返回 429 状态码和对应的提示信息。这样前端就能根据状态码做友好提示,而不是直接崩掉。
@RestControllerAdvice
public class RateLimitExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResultVO> handleBusiness(BusinessException e) {
if (e.getMessage().contains("请求太频繁")) {
return ResultVO.error(429, e.getMessage());
}
return ResultVO.error(e.getCode(), e.getMessage());
}
}
效果怎么样?直接上压力测试。用 curl 模拟 20 个并发请求,可以看到:前 5 个请求正常返回,后面的请求全部被拦截,返回 429 状态码和提示信息。限流策略生效,稳稳的。
# 模拟 20 个并发请求
for i in {1..20}; do
curl -X GET http://localhost:9090/api/test &
done
# 正常响应:{"code":200,"message":"成功"}
# 被限响应:{"code":429,"message":"请求太频繁,请稍后重试"}
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8