如何设置servlet中并发请求数的限制? [英] How to set limit to the number of concurrent request in servlet?

查看:277
本文介绍了如何设置servlet中并发请求数的限制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个servlet,它将pdf文件返回给客户端Web浏览器。
我们不想冒任何风险,当请求数量过多时,服务器就会瘫痪。

I got this servlet which return a pdf file to the client web browser. We do not want to risk any chance that when the number of request is too much, the server is paralyzed.

我们想要申请级别(程序)设置并发请求数限制的方法,并在达到限制时向浏览器返回错误消息。我们需要在应用程序级别执行它,因为我们在开发级别(tomcat)和生产级别(websphere)中有不同的servlet容器。

We would like to make an application level (program) way to set a limit in the number of concurrent request, and return a error message to the browser when the limit is reached. We need to do it in applicantion level because we have different servlet container in development level(tomcat) and production level(websphere).

我必须强调,我想控制最大请求数而不是会话数。用户可以使用相同的会话通过服务器发送多个请求。

I must emphasize that I want to control the maximum number of request instead of session. A user can send multiple request over the server with the same session.

任何想法?
我曾考虑使用静态计数器来跟踪请求的数量,但这会引发竞争条件的问题。

Any idea? I've thought about using a static counter to keep track of the number of request, but it would raise a problem of race condition.

推荐答案

我建议编写一个简单的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 的定义。

这篇关于如何设置servlet中并发请求数的限制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆