自定义注解+AOP+Guava实现限流
一.引入AOP和Guava依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>30.1.1-jre</version>
</dependency>
</dependencies>
二.自定义限流注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LimitFlow {
String name() default "";
double token() default 10;
}
三.定义Aop
@Component
@Aspect
public class LimitFlowAop {
private ConcurrentHashMap<String, RateLimiter> concurrentHashMap = new ConcurrentHashMap<>();
@Pointcut(value = "@annotation(com.jw.annotation.LimitFlow)")
private void limitFlowControl(){
}
@Around(value = "limitFlowControl()")
public Object around(ProceedingJoinPoint joinPoint){
MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
LimitFlow limitFlow = methodSignature.getMethod().getDeclaredAnnotation(LimitFlow.class);
String name = limitFlow.name();
double token = limitFlow.token();
RateLimiter rateLimiter = concurrentHashMap.get(name);
if (rateLimiter == null){
rateLimiter = RateLimiter.create(token);
concurrentHashMap.put(name,rateLimiter);
}
if (!rateLimiter.tryAcquire()) {
return "服务器繁忙!!";
}
try {
Object proceed = joinPoint.proceed();
return proceed;
} catch (Throwable throwable) {
throwable.printStackTrace();
return "发送错误!!";
}
}
}
1.为什么使用环绕通知???
因为只有环绕通知可以决定是否执行目标方法!!
2.切点使用annotation的方式
对被自定义注解标注的目标方法进行增强
3.通过反射获取注解的属性值,name和token,并创建限流器RateLimiter
对目标方法进行限流
四.测试
超出注解中规定的QPS,则访问不到接口!!
从而达到限流的目的