/*api接口拦截处理,设置接口访问上限开始*/
// 作为标识该接口的key值
String methodKey = handlerMethod.getBean().getClass().getName();
// 如果该方法(接口)上有Delay注解,则获取
AccessLimit delay = handlerMethod.getMethodAnnotation(AccessLimit.class);
if (delay != null) {
Long currentTime = System.currentTimeMillis();
if (!lastTimeMap.containsKey(methodKey)) {
// 接口被第一次访问,没有lastTime 放行
lastTimeMap.put(methodKey, currentTime);
} else {
// 方法正在被频繁访问,访问间隔小于delay.time(),请稍后重试
if (currentTime - lastTimeMap.get(methodKey) < delay.time()) {
logger.info("【频繁访问】,已被拦截");
String responseMsg = String.format("提示:访问过于频繁,每秒1万次请求已触发系统阈值,当前请求已被拦截,请稍后重试!", delay.time() / 1000);
response.setContentType("application/json;charset=utf-8"); // 不设置中文会出现乱码
response.getWriter().write(responseMsg);
// 拦截
return false;
} else {
// 大于间隔,更新接口上一次被成功访问的时间
lastTimeMap.put(methodKey, currentTime);
}
}
}
/*api接口拦截处理,设置接口访问上限结束*/



发表评论: