All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ghp.request.aspect.RequestLimitAspect Maven / Gradle / Ivy

package com.ghp.request.aspect;


import com.ghp.request.annotation.RequestLimit;
import com.ghp.request.enums.RequestLimitStrategy;
import com.ghp.request.exception.RequestLimitException;
import com.ghp.request.limiter.Limiter;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @author ghp
 * @title
 * @description
 */
@Aspect
@Component
public class RequestLimitAspect {

    /**
     * 前置通知(相当于一个拦截器),在所有添加了 RequestLimit 注解的前面执行
     *
     * @param joinPoint              切入点
     * @param requestLimitAnnotation 注解
     */
    @Before("@annotation(requestLimitAnnotation)")
    public void rateLimitCheck(JoinPoint joinPoint, RequestLimit requestLimitAnnotation) {
        String methodName = joinPoint.getSignature().getName();
        String message = requestLimitAnnotation.message();
        RequestLimitStrategy strategy = requestLimitAnnotation.strategy();
        Limiter limiter = strategy.getLimiter();
        // 调用限流方法
        boolean isLimited = true;
        synchronized (methodName.intern()) {
            isLimited = limiter.limit(methodName, requestLimitAnnotation);
        }
        if (isLimited) {
            // 发生限流则抛一个异常
            throw new RequestLimitException(message);
        }
    }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy