代码实现
当使用Spring Boot框架时,可以借助Spring框架中提供的注解和AOP(面向切面编程)功能来实现限流功能。下面是一个基于原子计数器的限流示例代码:
首先,我们需要添加以下依赖到pom.xml
文件中:
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Google Guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>29.0-jre</version>
</dependency>
</dependencies>
接下来,我们创建一个自定义注解 @RateLimit
,用于标记需要限制流量的方法:
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 RateLimit {
int value() default 10; // 限流速率,默认为每秒10次
}
然后,创建一个切面类 RateLimitAspect
,用于在被 @RateLimit
注解标记的方法执行前进行限流操作:
import com.google.common.util.concurrent.AtomicLongMap;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
@Aspect
@Component
public class RateLimitAspect {
private AtomicLongMap<String> counterMap = AtomicLongMap.create();
@Before("@annotation(rateLimit)")
public void checkRateLimit(JoinPoint joinPoint, RateLimit rateLimit) throws Exception {
String methodName = joinPoint.getSignature().toLongString();
int limit = rateLimit.value();
long count = counterMap.incrementAndGet(methodName);
if (count > limit) {
counterMap.put(methodName, limit); // 限制计数器的值为指定限流速率
throw new Exception("Rate limit exceeded.");
}
// 设置定时任务,每秒清零计数器
new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(1);
counterMap.remove(methodName);
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
}
最后,在Spring Boot的主类上添加注解 @EnableAspectJAutoProxy
来启用AOP功能,并将切面类 RateLimitAspect
添加到Spring的容器中:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication
@EnableAspectJAutoProxy
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
现在,我们就可以在需要限制流量的方法上添加 @RateLimit
注解来实现限流。例如:
@RestController
public class MyController {
@RateLimit(value = 5) // 每秒最多允许5次请求
@GetMapping("/myEndpoint")
public String myEndpoint() {
// 执行业务逻辑
return "Hello, World!";
}
}
在上述示例中,我们通过在 MyController
类的 myEndpoint()
方法上添加 @RateLimit
注解来限制每秒最多只能执行5次请求。如果超过限定的请求数,将抛出异常 “Rate limit exceeded.”。
请注意,上述示例中使用了Google Guava库中的 AtomicLongMap
类来实现原子计数器。同时,我们也在切面类中设置了一个定时任务,每秒清零计数器。
缺点:
如果有个需求对于某个接口 /query 每分钟最多允许访问 200 次,假设有个用户在第 59 秒的最后几毫秒瞬间发送 200 个请求,当 59 秒结束后 Counter 清零了,他在下一秒的时候又发送 200 个请求。
那么在 1 秒钟内这个用户发送了 2 倍的请求,这个是符合我们的设计逻辑的,这也是计数器方法的设计缺陷,系统可能会承受恶意用户的大量请求,甚至击穿系统。