我建议编写一个简单的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 code 429 (Too Many Requests)
// see http://tools.ietf.org/html/rfc6585#page-3
}
} finally {
synchronized (lock) {
count--;
}
}
}
}
或者你可以把这个逻辑放到你的HttpServlet中.它只是一个更清洁,更可重复使用的过滤器.您可能希望通过web.xml配置限制,而不是对其进行硬编码.