Search in sources :

Example 1 with AccessLimit

use of com.chao.cloud.common.extra.access.annotation.AccessLimit in project chao-cloud by chaojunzi.

the class AccessLimitProxy method around.

// 环绕拦截
@Around(value = "@annotation(org.springframework.web.bind.annotation.RequestMapping)")
public Object around(ProceedingJoinPoint pdj) throws Throwable {
    // 获取method 中的注解
    Method method = this.getMethod(pdj);
    AccessLimit access = method.getAnnotation(AccessLimit.class);
    // 
    HttpServletRequest request = this.getRequest();
    // 获取key=ip+port+url
    String ip = ServletUtil.getClientIP(request, null);
    String key = StrUtil.format("{}:{}@{}", ip, request.getRemotePort(), request.getRequestURI());
    Integer val = null;
    // 
    long timeout = ObjectUtil.isNull(access) ? AccessLimit.DEFAULT_TIME : access.timeout();
    // 
    boolean check = ObjectUtil.isNull(access) || access.enable();
    if (check) {
        // 开始校验
        val = accessLimitCache.get(key, false);
        log.info("[access:key={},count={}]", key, ObjectUtil.isNull(val) ? 0 : val);
        int count = ObjectUtil.isNull(access) ? AccessLimit.DEFAULT_COUNT : access.count();
        if (val != null && val >= count) {
            throw new BusinessException("HTTP请求超出设定的限制");
        }
    }
    // 执行
    try {
        return pdj.proceed();
    } catch (Throwable e) {
        if (check) {
            // 异常记录+1
            accessLimitCache.put(key, ObjectUtil.isNull(val) ? 1 : val + 1, timeout);
        }
        throw e;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) BusinessException(com.chao.cloud.common.exception.BusinessException) AccessLimit(com.chao.cloud.common.extra.access.annotation.AccessLimit) Method(java.lang.reflect.Method) ProceedingJoinPoint(org.aspectj.lang.ProceedingJoinPoint) Around(org.aspectj.lang.annotation.Around)

Aggregations

BusinessException (com.chao.cloud.common.exception.BusinessException)1 AccessLimit (com.chao.cloud.common.extra.access.annotation.AccessLimit)1 Method (java.lang.reflect.Method)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 ProceedingJoinPoint (org.aspectj.lang.ProceedingJoinPoint)1 Around (org.aspectj.lang.annotation.Around)1