天天看點

自定義注解+AOP+Guava實作限流一.引入AOP和Guava依賴二.自定義限流注解三.定義Aop四.測試

自定義注解+AOP+Guava實作限流

  • 一.引入AOP和Guava依賴
  • 二.自定義限流注解
  • 三.定義Aop
  • 四.測試

一.引入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,則通路不到接口!!

進而達到限流的目的

自定義注解+AOP+Guava實作限流一.引入AOP和Guava依賴二.自定義限流注解三.定義Aop四.測試

繼續閱讀