1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| @Component class ReqLimitInterceptor implements HandlerInterceptor { private static ConcurrentHashMap<String, ExpiringMap<Object, Object>> book = new ConcurrentHashMap<String, ExpiringMap<Object, Object>>();
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { String url = request.getParameter("robotUrl")==null?request.getRequestURI():request.getParameter("robotUrl"); HandlerMethod handlerMethod = (HandlerMethod) handler; RequestLimit annotation = handlerMethod.getMethodAnnotation(RequestLimit.class); if (annotation == null) { return true; } ExpiringMap<Object, Object> expiringMap = book.get(request.getRequestURI()) == null? ExpiringMap.builder().variableExpiration().build():book.get(request.getRequestURI()); Integer count = (Integer) expiringMap.get(url); if(count == null) { count = 0; } if (count >= annotation.count()) { throw new TechnologyException("ERR-0300", new Object[] {annotation.time(), annotation.count()}); } else if (count == 0){ expiringMap.put(url, count + 1, ExpirationPolicy.CREATED, annotation.time(), TimeUnit.MILLISECONDS); } else { expiringMap.put(url, count + 1); } book.put(request.getRequestURI(), expiringMap); return true; }
@Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
}
@Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
} }
|