Spring Cloud Micro security service reform limiting the combat _6-4_

Examples of the use of limiting frame 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;
        }
    }
}
Before the flow restrictor filter, loading a first filter of the filter chain SpringSecurity
  

 

 carry out.

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

 

Chapter VI summary

 

 

  

Guess you like

Origin www.cnblogs.com/lihaoyang/p/12501407.html