高併發下接口限流技術gauva(谷歌的框架) MySql最大鏈接數3000;api
原理:框架每秒向桶裏放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