我建议写一个简单的servlet
Filter。在您的服务器上对其
web.xml进行配置,以应用于您要限制并发请求数的路径。代码看起来像这样:
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 pre 429 (Too Many Requests) // see http://tools.ietf.org/html/rfc6585#page-3 } } finally { synchronized (lock) { count--; } } }}
或者,您也可以将此逻辑放入您的
HttpServlet。它只是更干净,更可重用
Filter。您可能希望通过
web.xml而不是硬编码来配置限制。
参考:
检查HTTP状态代码429的定义。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)