例子使用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过滤器链的第一个过滤器前
  Spring Cloud微服务安全实战_6-6_限流的改造

 


 完成。

代码:https://github.com/lhy1234/springcloud-security/tree/chapt-6-5-ratelimit

 

Spring Cloud微服务安全实战_6-6_限流的改造

 

 欢迎关注个人公众号一起交流学习:

Spring Cloud微服务安全实战_6-6_限流的改造

  

相关文章:

  • 2022-01-14
  • 2021-09-18
  • 2021-05-26
  • 2021-08-13
  • 2022-01-10
  • 2021-11-18
  • 2021-07-19
  • 2021-11-18
猜你喜欢
  • 2021-09-07
  • 2022-01-25
  • 2022-02-07
  • 2021-09-12
  • 2022-02-07
  • 2022-01-04
  • 2022-01-02
相关资源
相似解决方案