随机代码

1@Component
2public class LimitFilter implements Filter {
3    private static final RateLimiter RATE_LIMITER = RateLimiter.create(1);
4    @Override
5    public void init(FilterConfig filterConfig) throws ServletException {
6
7    }
8
9    @Override
10    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
11                         FilterChain filterChain) throws IOException, ServletException {
12        if (RATE_LIMITER.tryAcquire()) {
13            System.out.println("通过");
14            filterChain.doFilter(servletRequest, servletResponse);
15        } else {
16            servletResponse.setCharacterEncoding("utf-8");
17            servletResponse.setContentType("text/html;charset=utf-8");
18            PrintWriter pw = servletResponse.getWriter();
19            pw.write("限流了。。。");
20            pw.close();
21            System.out.println("限流了");
22
23        }
24    }
25
26    @Override
27    public void destroy() {
28
29    }
30}
参考地址:spring cloud微服务间限流,使用jMeter性能测试高并发

代码交流 2021