在Java中,可以使用自定义注解来实现限流功能。
```java
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.METHOD)
 public @interface RateLimit {
     int value() default 1;
 }
 ```
上面的代码定义了一个名为`RateLimit`的注解,通过给方法添加这个注解,可以限制方法的访问频率。
然后,创建一个切面类来拦截被`RateLimit`注解标注的方法:
```java
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.TimeUnit;
import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
@Aspect
 public class RateLimitAspect {
private ConcurrentHashMap<String, Integer> counterMap = new ConcurrentHashMap<>();
    @Around("@annotation(rateLimitAnnotation)")
     public Object rateLimit(ProceedingJoinPoint joinPoint, RateLimit rateLimitAnnotation) throws Throwable {
         String methodName = joinPoint.getSignature().getName();
        // 检查方法名对应的计数器是否存在
         counterMap.putIfAbsent(methodName, 0);
        int counter = counterMap.get(methodName);
         int limit = rateLimitAnnotation.value();
        if (counter >= limit) {
             throw new RuntimeException("Rate limit exceeded");
         }
        // 执行目标方法
         Object result = joinPoint.proceed();
        // 计数器加1
         counterMap.put(methodName, counter + 1);
        return result;
     }
 }
 ```
`RateLimitAspect`类是一个切面类,通过`@Around`注解实现对被`RateLimit`注解标注的方法的拦截。
最后,使用这个注解和切面示例:
```java
 public class Main {
     @RateLimit(5) // 每秒限制调用次数为5次
     public void doSomething() {
         System.out.println("Doing something...");
     }
    public static void main(String[] args) {
         // 创建切面
         RateLimitAspect aspect = new RateLimitAspect();
        // 创建代理对象
         Main mainObj = (Main) aspect.aspectOf(Main.class);
        // 调用被限流的方法
         for (int i = 0; i < 10; i++) {
             try {
                 mainObj.doSomething();
             } catch (RuntimeException e) {
                 System.out.println("Rate limit exceeded");
             }
             
             // 每次调用后暂停一秒钟
             try {
                 TimeUnit.SECONDS.sleep(1);
             } catch (InterruptedException e) {
                 e.printStackTrace();
             }
         }
     }
 }
 ```
上面的例子中,`Main`类中的`doSomething`方法被`@RateLimit(5)`注解标注,表示该方法在1秒内最多只能被调用5次。通过切面拦截,如果超过次数限制则会抛出`RuntimeException`异常。
在`main`方法中,我们创建了`RateLimitAspect`切面实例,并通过`aspectOf`方法获得代理对象。然后,我们调用被限流的`doSomething`方法,可以看到在一秒内只能调用5次,超出限制后会打印"Rate limit exceeded"。
这是一个简单的基于注解的限流实现,你可以根据自己的需求进行扩展和适应。

一个注解实现分布式锁
springboot 调用外部接口的21种方式
分布式事务4种实现方式
又被面试官问到 Redis的多线程了
分布式系统中的CAP理论,面试必问,你理解了嘛?
多线程开发带来的问题与解决方法
有了MyBatis-Flex ,再也不用mybatis-plus了
mysql分页查询数据量大的时候为什么慢,怎么优化
程序员职场晋升50条具体建议
mysql 50条 优化建议
同事离职,领导让你兼他的工作你不愿意,怎么办
MySQL 巨坑:永远不要在 MySQL 中使用 UTF-8!!请使用utf8mb4
文章首发自公众号《java知路》



















