在Java中,可以使用注解来实现限流。以下是一个简单的示例:
1. 首先,创建一个自定义注解`@RateLimiter`:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RateLimiter { double permitsPerSecond(); }
2. 然后,创建一个限流器类`RateLimiterAspect`,并实现限流逻辑:
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; @Aspect @Component public class RateLimiterAspect { private static final AtomicInteger counter = new AtomicInteger(0); @Around("@annotation(rateLimiter)") public Object around(ProceedingJoinPoint joinPoint, RateLimiter rateLimiter) throws Throwable { double permitsPerSecond = rateLimiter.permitsPerSecond(); long interval = (long) (1000 / permitsPerSecond); long currentTime = System.currentTimeMillis(); long lastTime = currentTime - interval; while (true) { int currentCounter = counter.get(); if (currentCounter > 0 && currentTime - lastTime < interval) { Thread.sleep(interval - (currentTime - lastTime)); currentTime = System.currentTimeMillis(); } else { if (counter.compareAndSet(currentCounter, currentCounter + 1)) { lastTime = currentTime; break; } } } return joinPoint.proceed(); } }
3. 最后,在需要限流的方法上添加`@RateLimiter`注解:
public class MyService { @RateLimiter(permitsPerSecond = 2) // 每秒允许2个请求 public void myMethod() { // 业务逻辑 } }
这样,当调用`myMethod`方法时,会根据`@RateLimiter`注解中设置的速率进行限流。