@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LimitRequest {
long time() default 60;
int count() default 1;
}
@Aspect
@Component
public class LimitRequestAspect {
@Autowired
private HttpServletRequest request;
@Autowired
private CacheComponent cacheComponent;
private static ConcurrentHashMap<String,Map<String, Integer>> book = new ConcurrentHashMap<>();
private static final String LIMIT_REQUEST = "limit_request";
private static final String LIMIT_REQUEST_EXCEPTION = "limit_request_exception";
@Pointcut("@annotation(limitRequest)")
public void excudeService(LimitRequest limitRequest) {
}
@Around("excudeService(limitRequest)")
public Object doAround(ProceedingJoinPoint pjp, LimitRequest limitRequest) throws Throwable {
ResultData resultData = new ResultData();
String userId = JwtUtil.getInstance().getIdByParseJWT(request);
String str = cacheComponent.get(LIMIT_REQUEST_EXCEPTION + userId);
if(StringUtils.isNotBlank(str)){
return resultData.fail("请休息一下三分钟后再试");
}
String count = cacheComponent.get(LIMIT_REQUEST + userId);
Integer uCount = StringUtils.isBlank(count) ? 0 : Integer.valueOf(count);
if (uCount >= limitRequest.count()) {
String srt = "requestException";
cacheComponent.set(LIMIT_REQUEST_EXCEPTION + userId, JSONObject.toJSONString(srt), 180L);
return resultData.fail("请休息一下三分钟后再试");
}else if(uCount == 0){
int setCount = uCount + 1;
cacheComponent.set(LIMIT_REQUEST + userId, JSONObject.toJSONString(setCount), limitRequest.time());
}else{
int setCount = uCount + 1;
cacheComponent.setValue(LIMIT_REQUEST + userId, JSONObject.toJSONString(setCount));
}
Object result = pjp.proceed();
return result;
}
}