单机版接口限流 Guava + 拦截器

最近有个需求是点赞,虽然现在用户量不高,但是用户可以连续点赞,所以做一个单机版的接口限流.

用的是Guava的RateLimiter

导入依赖包


    com.google.guava
    guava
    23.0

主要是对接口进行拦截, 然后限流.

写一个拦截器

/**
 * 接口限流拦截器
 * @author linnine
 */
@Slf4j
@Component
public class RateLimiterInterceptor implements HandlerInterceptor {

    private static final RateLimiter rateLimiter = RateLimiter.create(1);
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!rateLimiter.tryAcquire()) {
            log.warn("限流中......");
            try {
                ServletOutputStream outputStream = response.getOutputStream();
                String resp = JsonUtil.toJsonStr(BizCode.CURRENT_LIMITING);
                outputStream.write(resp.getBytes());
                outputStream.flush();
                outputStream.close();
            } catch (IOException ioException) {
                ExceptionUtil.catchExceptionLog(ioException);
            }
            return false;
        }
        return true;
    }

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

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

}

然后在配置文件中 引用

@Slf4j
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Value("${interceptor.api-path-patterns}")
    private String[] apiPathPatterns;

    @Value("${interceptor.api-exclude-path-patterns}")
	private String[] apiExcludePathPatterns;
	
    @Resource
    private RateLimiterInterceptor rateLimiterInterceptor;

    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("pathPatterns={}", JsonUtil.toJsonStr(apiPathPatterns));
        registry.addInterceptor(rateLimiterInterceptor)
        		.addPathPatterns(apiPathPatterns)
        		.excludePathPatterns(apiExcludePathPatterns);
        super.addInterceptors(registry);
    }
}	

配置文件这么写

interceptor:
  #拦截哪些接口
  api-path-patterns: /cheer/\**, /user/**
  #哪些接口不拦截
  api-exclude-path-patterns:  /cheer/list

你可能感兴趣的:(spring,boot,spring,boot)