Throttle HTTP request in Java Servlet

2019-06-18 06:34发布

In a java servlet, how can I throttle http requests coming from users based on the client's IP address? I do not want to serve more than X requests per second coming from a particular source IP address where X is configurable and having practical values in [0.1; 10] range (from 1 request in 10 sec to 10 requests per sec).

5条回答
倾城 Initia
2楼-- · 2019-06-18 07:30

Check if the container you are using provides this kind of Denial Of Service. If no, then you would have to go with a filter.

ServletRequest.getRemoteHost() gives you access to the client IP.

查看更多
唯我独甜
3楼-- · 2019-06-18 07:31

As @EJP said, using a Filter with a HashMap that stores the last access time by IP address key. 10 requests a second would translate to 100ms between calls, minimum. Sending a server busy error code back and killing the request will quickly close the resources used by the connection. There are prebuilt solutions for Apache if that's an option for you.

查看更多
Deceive 欺骗
4楼-- · 2019-06-18 07:33

The owasp-esapi-java project, hosted at code.google.com, has an implementation of a throttle filter that you can use "as is" or use as inspiration for your own.

You can check the code at the following link:

http://code.google.com/p/owasp-esapi-java/source/browse/trunk/src/main/java/org/owasp/esapi/filters/RequestRateThrottleFilter.java

查看更多
Bombasti
5楼-- · 2019-06-18 07:34

I would write a Filter for that task.

查看更多
Rolldiameter
6楼-- · 2019-06-18 07:36

Use a servlet filter: if you're on Jetty 7.0 or higher there is this

查看更多
登录 后发表回答