1. 引入 hutool 依赖

在项目的 pom.xml 文件中加入 hutool 的依赖:

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.2</version>
</dependency>
  1. 自定义注解

定义一个注解,用于标识需要限流的接口:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimit {
    int value() default 10;
}

该注解有一个 value 属性,用于指定限流的阈值,默认为 10。

  1. AOP 实现限流

定义一个 AOP 切面,拦截带有 RateLimit 注解的方法,进行限流操作:

@Aspect
@Component
public class RateLimitAspect {
    private static final Map<String, RateLimiter> RATE_LIMITER_MAP = new ConcurrentHashMap<>();

    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        String key = joinPoint.getSignature().toString();
        RateLimiter rateLimiter = RATE_LIMITER_MAP.computeIfAbsent(key, k -> RateLimiter.create(rateLimit.value()));
        if (!rateLimiter.tryAcquire()) {
            throw new RuntimeException("接口限流");
        }
        return joinPoint.proceed();
    }
}

该 AOP 切面实现了 Around 通知,用于拦截带有 RateLimit 注解的方法。在拦截到方法后,根据方法签名获取一个 RateLimiter 实例,如果该实例当前已经达到了限流阈值,则抛出一个 RuntimeException 异常,否则执行原方法。

  1. 在接口上添加 RateLimit 注解

在需要进行限流的接口的方法上添加 RateLimit 注解,指定限流的阈值:

@RestController
public class TestController {
    @GetMapping("/test")
    @RateLimit(5)
    public String test() {
        return "test";
    }
}

以上代码表示 /test 接口每秒钟最多只能访问 5 次。

参考链接:https://www.hutool.cn/docs/#/aop/AOP%E7%9A%84%E4%BD%BF%E7%94%A8-RateLimiter%E9%99%90%E6%B5%81

Java 使用 hutool 和 自定义注解和 AOP 对接口进行限流

原文地址: https://www.cveoy.top/t/topic/bTaR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录