时机:请求被转发之前调用
令牌桶限流:
令牌桶算法已经有开源的软件了,google的开源工具,直接用google开发好的类即可:
com.google.common.util.concurrent.RateLimiter;
其他部分是类似的:
@Component
public class RateLimitFilter extends ZuulFilter {
private static final RateLimiter RATE_LIMITER = RateLimiter.create(100);
@Override
public String filterType() {
return PRE_TYPE;
}
@Override
public int filterOrder() {
// 这个值相当于是最优先的
return SERVLET_DETECTION_FILTER_ORDER - 1;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
if(!RATE_LIMITER.tryAcquire()) {
throw new RateLimitException();
}
return null;
}
}