高并发下接口限流技术gauva(谷歌的框架)
原理:框架每秒向桶里放100个令牌,接口请求来了先去拿令牌,拿到令牌后才能继续向后走,否则不允许向后执行;当接口请求太频繁的话就会拿不上令牌,此时就起到了限流的作用; 我们在网关层做一个限流:
1 /** 2 * 订单限流 3 */ 4 @Component 5 public class OrderRateLimiterFilter extends ZuulFilter { 6 7 8 //每秒产生1000个令牌 9 private static final RateLimiter RATE_LIMITER = RateLimiter.create(1000); 10 11 @Override 12 public String filterType() { 13 return PRE_TYPE; 14 } 15 16 @Override 17 public int filterOrder() { 18 return -4; 19 } 20 21 22 23 @Override 24 public boolean shouldFilter() { 25 26 27 RequestContext requestContext = RequestContext.getCurrentContext(); 28 HttpServletRequest request = requestContext.getRequest(); 29 30 //只对订单接口限流 31 if ("/apigateway/api/v1/order/save".equalsIgnoreCase(request.getRequestURI())){ 32 return true; 33 } 34 35 return false; 36 } 37 38 @Override 39 public Object run() throws ZuulException { 40 RequestContext requestContext = RequestContext.getCurrentContext(); 41 //RATE_LIMITER.tryAcquire()表示立马去拿令牌,只要拿不到就拦截;也可以设置一段时间内拿不到再拦截 42 if(!RATE_LIMITER.tryAcquire()){ 43 requestContext.setSendZuulResponse(false); 44 requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value()); 45 } 46 return null; 47 } 48 49 50 51 } 52