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;
}
}
Aggregations