自定义注解+AOP+Guava实现限流

自定义注解+AOP+Guava实现限流

  • 一.引入AOP和Guava依赖
  • 二.自定义限流注解
  • 三.定义Aop
  • 四.测试

一.引入AOP和Guava依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
        dependency>

        <dependency>
            <groupId>com.google.guavagroupId>
            <artifactId>guavaartifactId>
            <version>30.1.1-jreversion>
        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,则访问不到接口!!
从而达到限流的目的

自定义注解+AOP+Guava实现限流_第1张图片

你可能感兴趣的:(springboot,guava,aop,自定义注解,限流,反射)