且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何设置servlet中并发请求数的限制?

更新时间:2023-10-28 15:35:34

我建议编写一个简单的servlet 过滤器。在 web.xml 中对其进行配置,以应用于要限制并发请求数的路径。代码看起来像这样:

I'd suggest writing a simple servlet Filter. Configure it in your web.xml to apply to the path that you want to limit the number of concurrent requests. The code would look something like this:

public class LimitFilter implements Filter {
    private int limit = 5;
    private int count;
    private Object lock = new Object();

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        try {
            boolean ok;
            synchronized (lock) {
                ok = count++ < limit;
            }
            if (ok) {
                // let the request through and process as usual
                chain.doFilter(request, response);
            } else {
                // handle limit case, e.g. return status code 429 (Too Many Requests)
                // see http://tools.ietf.org/html/rfc6585#page-3
            }
        } finally {
            synchronized (lock) {
                count--;
            }           
        }
    }
}

或或者你可以把这个逻辑放到 HttpServlet 中。它只是更清洁,更可重复使用过滤器。您可能希望通过 web.xml 配置限制,而不是对其进行硬编码。

Or alternatively you could just put this logic into your HttpServlet. It's just a bit cleaner and more reusable as a Filter. You might want to make the limit configurable through the web.xml rather than hard coding it.

参考:

检查 HTTP状态代码429 的定义。