我最终放弃了尝试寻找AOP解决方案的方法,而是创建了一个Spring
Interceptor。拦截器将处理
preHandle所有请求,并监视其处理程序为的请求
@RateLimited。
@Componentpublic class RateLimitingInterceptor extends HandlerInterceptorAdapter { @Autowired private final RateLimitService rateLimitService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (HandlerMethod.class.isAssignableFrom(handler.getClass())) { rateLimit(request, (HandlerMethod)handler); } return super.preHandle(request, response, handler); } private void rateLimit(HttpServletRequest request, HandlerMethod handlerMethod) throws TooManyRequestsException { if (handlerMethod.getMethodAnnotation(RateLimited.class) != null) { String ip = request.getRemoteAddr(); int secondsToWait = rateLimitService.secondsUntilNextAllowedInvocation(ip); if (secondsToWait > 0) { throw new TooManyRequestsException(secondsToWait); } else { rateLimitService.recordInvocation(ip); } } }}


