王剑编程网

分享专业编程知识与实战技巧

Spring AOP接口限流实战!三行注解解决高并发,代码可复制

为什么你的系统总在半夜崩溃?

某电商平台大促期间,一个抢购接口被狂刷每秒10万次请求,数据库直接瘫痪!接口限流就像给系统装上“安全阀”,精准控制流量,防止服务器被压垮。本文手把手教你用Spring AOP实现限流,代码可直接用于生产环境!(应某网友评论,写一篇关于削峰注解的文章)


一、5分钟快速上手(含完整代码)

1. 添加Spring AOP依赖



    org.springframework.boot
    spring-boot-starter-aop

2. 自定义限流注解

@Target(ElementType.METHOD) // 只能用在方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时生效
public @interface RateLimit {
    int value() default 100; // 默认每秒100次请求
}

3. 核心限流切面(逐行解析)

@Aspect
@Component
public class RateLimitAspect {
    // 使用线程安全的Map存储计数器(Key:方法名,Value:计数器)
    private final Map counters = new ConcurrentHashMap<>();
    // 存储每个方法的时间窗口(Key:方法名,Value:时间戳秒数)
    private final Map timestamps = new ConcurrentHashMap<>();

    @Around("@annotation(rateLimit)") // 拦截带@RateLimit注解的方法
    public Object doLimit(ProceedingJoinPoint pjp, RateLimit rateLimit) throws Throwable {
        String methodName = pjp.getSignature().toLongString(); // 获取完整方法名
        int limit = rateLimit.value(); // 读取注解中的限流值
        
        // 1. 获取当前时间窗口(每秒一个窗口)
        long nowSeconds = System.currentTimeMillis() / 1000;
        Long lastWindow = timestamps.get(methodName);
        
        // 2. 如果时间窗口过期(超过1秒),重置计数器
        if (lastWindow == null || nowSeconds > lastWindow) {
            counters.put(methodName, new AtomicInteger(0)); // 重置计数器
            timestamps.put(methodName, nowSeconds); // 记录新时间窗口
        }
        
        // 3. 计数器+1,并检查是否超限
        AtomicInteger counter = counters.get(methodName);
        int currentCount = counter.incrementAndGet(); // 原子性递增
        
        if (currentCount > limit) {
            throw new RuntimeException("请求太频繁,请稍后再试!"); // 抛出限流异常
        }
        
        return pjp.proceed(); // 4. 执行原方法
    }
}

二、代码逐行详解(小白秒懂)

关键点1:为什么用ConcurrentHashMap?

  • ConcurrentHashMap是线程安全的Map,防止多线程下计数器错乱
  • AtomicInteger保证计数器的原子性操作(避免synchronized性能损耗)

关键点2:时间窗口设计原理

  • 将时间划分为1秒的窗口(nowSeconds = 当前毫秒/1000)
  • 每个窗口独立计数,例如:
    • 第1秒:0~1000毫秒,允许100次请求
    • 第2秒:1001~2000毫秒,计数器重新从0开始

关键点3:@Around注解的作用

  • 在目标方法执行前后插入限流逻辑
  • pjp.proceed()表示执行原方法

三、实战测试(Postman验证)

1. 在Controller中使用注解

@RestController
public class UserController {
    
    // 限制每秒最多5次请求
    @RateLimit(5)
    @GetMapping("/userInfo")
    public String getUserInfo() {
        return "用户信息";
    }
}

2. 用Postman连续发送请求

  • 第1~5次请求:正常返回用户信息
  • 第6次请求:返回错误提示
{
  "timestamp": "2024-05-20T03:12:45.123+00:00", 
  "status": 500, 
  "error": "Internal Server Error", 
  "message": "请求太频繁,请稍后再试!"
}

四、生产环境优化方案

方案1:分布式限流(Redis版)

@Autowired
private RedisTemplate redisTemplate;

public Object doLimit(ProceedingJoinPoint pjp, RateLimit rateLimit) throws Throwable {
    String key = "rate_limit:" + pjp.getSignature().getName();
    int limit = rateLimit.value();
    
    // 使用Lua脚本保证原子性
    String luaScript = 
        "local current = redis.call('incr', KEYS[1])\n" +
        "if current == 1 then\n" +
        "    redis.call('expire', KEYS[1], 1)\n" +
        "end\n" +
        "return current";
    
    Long count = redisTemplate.execute(
        new DefaultRedisScript<>(luaScript, Long.class),
        Collections.singletonList(key)
    );
    
    if (count != null && count > limit) {
        throw new RuntimeException("系统繁忙,请重试");
    }
    
    return pjp.proceed();
}

优势:适用于集群环境,所有服务器共享计数器


方案2:平滑限流(Guava RateLimiter)

private final RateLimiter rateLimiter = RateLimiter.create(100); // 每秒100个令牌

@Around("@annotation(RateLimit)")
public Object limit(ProceedingJoinPoint pjp) throws Throwable {
    if (!rateLimiter.tryAcquire()) { // 尝试获取令牌
        throw new RuntimeException("系统限流中");
    }
    return pjp.proceed();
}

优势:允许突发流量(如1秒内瞬间处理200个请求)


五、避坑指南(真实项目经验)

  1. 时间窗口不同步问题
  • 多服务器环境下,各机器本地时间可能不一致,需使用Redis服务器时间
  1. 计数器重置的并发问题
  • 在重置计数器和更新时间窗口时,要保证原子性操作(如用Redis的Lua脚本)
  1. 异常处理策略
  • 自定义业务异常,返回友好提示:
@ExceptionHandler(RateLimitException.class)
public ResponseEntity handleRateLimit(RateLimitException e){ 
  return ResponseEntity.status(429).body("请求过快,请稍后再试"); 
}

六、限流算法对比(选型参考)

算法

实现难度

特点

适用场景

计数器法

★☆☆☆☆

简单粗暴

低频接口

滑动窗口

★★★☆☆

更精准的时间控制

支付核心接口

令牌桶

★★☆☆☆

允许突发流量

秒杀系统

漏桶算法

★★☆☆☆

恒定速率处理请求

第三方API调用



七、结语:立即保护你的核心接口!

通过Spring AOP实现限流,就像给系统穿上“防弹衣”。本文代码可直接复制到项目中,关注我,下期分享《自定义注解》,让你全面使用aop!

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言