例子使用Guava的限流框架
GatewayRateLimitFilter :
/** * 限流过滤器 */ public class GatewayRateLimitFilter extends OncePerRequestFilter { private RateLimiter rateLimiter = RateLimiter.create(1); @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { System.err.println("0 rate limit "); if(rateLimiter.tryAcquire()){ filterChain.doFilter(request,response); }else { response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value()); response.setContentType("application/json"); response.getWriter().write("{"error":"too many request"}"); response.getWriter().flush(); return; } } }
限流过滤器,加载SpringSecurity过滤器链的第一个过滤器前
完成。
代码:https://github.com/lhy1234/springcloud-security/tree/chapt-6-5-ratelimit
第六章总结