Google's Guava is an artifact added to the JDK, and deserves to be studied well.
Access restrictions for general web systems can be implemented using the container itself, such as Tomcat, which can be configured with a limit of connection number on the connector, and the servlet thread limit.
Sometimes the system is complicated and wants to provide different ratelimiter for different services, such as the higher rate of database operation, the rate at which the memory can be processed, and the possibility to provide the limiter service for the cluster.
How speed limit is a public topic, there are a lot of algorithms and implementations involved, and it's interesting to look at Calvin's Springside4 Wiki's description of the chapter and write it very well.
Here is a record of how the system uses Ratelimiter to limit the access rate of all spring accesses during the practice process, and the simple version, without the input parameters required for the injection of Ratelimiter.
1. Define the filter
Public class ratelimiterfilter implements Filter { Private StaticLogger Logger = Logger.getlogger (Ratelimiterfilter.class);PrivateRatelimiter limiter =NULL; Public void Init(filterconfig config)throwsservletexception {limiter = Ratelimiter.create ( -);//100 request per second} Public void Destroy() { } Public void DoFilter(ServletRequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {httpservletrequest req = (httpservletrequest) request; HttpServletResponse res = (httpservletresponse) response;if(Limiter.tryacquire ()) {if(Logger.istraceenabled ()) {Logger.trace ("Get access:"); } chain.dofilter (Request, Response)}Else{Logger.info ("System limitation reached!"); Req.getrequestdispatcher ("/web-inf/jsp/error/429.jsp"). Forward (Req,res); } }}
2. Modify Web. xml
<filter> <filter-name>Ratelimiter</filter-name> <filter-class>Ratelimiterfilter</filter-class> </filter> <filter-mapping> <filter-name>Ratelimiter</filter-name> <servlet-name>Springmvc</servlet-name> </filter-mapping>
3. Ratelimiter package introduced in Maven
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>18.0</version></dependency>
Done!
The use of guava Ratelimiter in Web applications