使用google的guova进行限流
1、guova的限流方式,在定时产生定量的令牌,令牌的数量限制了流量
2、增加一个订单接口限流类OrderRateFilter,继承ZuulFilter,并重载方法;filterType、filterOrder、shouldFilter、run
????filterType中return PRE_TYPE;
????fileterOrder中应该优先级最高,设为-4
????shouldFilter中设置限流的方法(类似于鉴权)
???? RequestContext requestContext= RequestContext.getCurrentContext();
HttpServletRequest httpServletRequest=requestContext.getRequest();
//System.out.println(httpServletRequest.getRequestURI());///apigateway/order/api/v1/orderfeignhystrix/save
//System.out.println(httpServletRequest.getRequestURL());//http://192.168.136.128:9000/apigateway/order/api/v1/orderfeignhystrix/save
?
if ("/apigateway/order/api/v1/orderfeignhystrix/save".equalsIgnoreCase(httpServletRequest.getRequestURI()))
{
return true;
}
????run中设置 ,获取令牌
????guava中需要增加令牌设置
????//每秒1000个令牌
????private static final RateLimiter RATE_LIMITER=RateLimiter.create(1000);
????
????在run中增加RATELIMITER.tryActquire();
????????如果未取到这返回过多的访问
????????
?
????????
?
if (!RATE_LIMITER.tryAcquire())
{
RequestContext requestContext=RequestContext.getCurrentContext();
requestContext.setSendZuulResponse(false);
requestContext.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
}
原文地址:https://www.cnblogs.com/programer-xinmu78/p/10551551.html