Sample code for SpringMVC current limiting

  • 2020-12-07 04:02:01
  • OfStack

In use SpringBoot do interface to access the current limit of the interface, how to do here, we can use google Guava package to do this, of course, we can realize the current limit, the current limiting Guava is proven we didn't have to go to the write one, if want to know the students can refer to our current limiting principle 1 under the relevant data, this article does not make oh come over.

Directions for use

Introduce Guava-related packages into the project

http://mvnrepository.com/artifact/com.google.guava/guava/21.0

maven project


<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
  <groupId>com.google.guava</groupId>
  <artifactId>guava</artifactId>
  <version>21.0</version>
</dependency>

gradle project


// https://mvnrepository.com/artifact/com.google.guava/guava
compile group: 'com.google.guava', name: 'guava', version: '21.0'

Write 1 interceptor for SpringMVC

SmoothBurstyInterceptor.java


import com.google.common.util.concurrent.RateLimiter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

public class SmoothBurstyInterceptor extends HandlerInterceptorAdapter {

  public enum LimitType {
    DROP,// discarded 
    WAIT // Waiting for the 
  }

  /**
   *  Current limiter 
   */
  private RateLimiter limiter;
  /**
   *  Current limiting way 
   */
  private LimitType limitType = LimitType.DROP;

  public SmoothBurstyInterceptor() {
    this.limiter = RateLimiter.create(10);
  }

  /**
   * @param tps     Limit traffic  ( Handling capacity per second )
   * @param limitType  Current limiting type : Waiting for the / discarded ( Reach flow limit )
   */
  public SmoothBurstyInterceptor(int tps, SmoothBurstyInterceptor.LimitType limitType) {
    this.limiter = RateLimiter.create(tps);
    this.limitType = limitType;
  }
  /**
   * @param permitsPerSecond  Number of new tokens per second 
   * @param limitType  Current limiting type : Waiting for the / discarded ( Reach flow limit )
   */
  public SmoothBurstyInterceptor(double permitsPerSecond, SmoothBurstyInterceptor.LimitType limitType) {
    this.limiter = RateLimiter.create(permitsPerSecond, 1000, TimeUnit.MILLISECONDS);
    this.limitType = limitType;
  }


  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (limitType.equals(LimitType.DROP)) {
      if (limiter.tryAcquire()) {
        return super.preHandle(request, response, handler);
      }
    } else {
      limiter.acquire();
      return super.preHandle(request, response, handler);
    }
    throw new Exception(" Network anomalies !");// Error message prompted to the page after the current limit has been reached. 
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    super.postHandle(request, response, handler, modelAndView);
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    super.afterCompletion(request, response, handler, ex);
  }

  public RateLimiter getLimiter() {
    return limiter;
  }

  public void setLimiter(RateLimiter limiter) {
    this.limiter = limiter;
  }
}

SpringMVC intercept configuration

WebConfig.java


@Component
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    //  Multiple interceptors 1 Three interceptor chains 
    registry.addInterceptor(new SmoothBurstyInterceptor(100, SmoothBurstyInterceptor.LimitType.DROP)).addPathPatterns("/**");
    // Current limiting can be configured as SmoothBurstyInterceptor.LimitType.DROP Discard the request or SmoothBurstyInterceptor.LimitType.WAIT Wait for, 100 Is the rate per second 
    super.addInterceptors(registry);
  }

}

Related articles: