SpringMVC 限流的示例代码
在使用SpringBoot做接口访问如何做接口的限流,这里我们可以使用google的Guava包来实现,当然我们也可以自己实现限流,Guava中的限流是久经考验的我们没必需重新再去写一个,如果想了解限流原理的同学可以自己查阅一下相关的资料,本文不作过来说明噢。
使用说明
在项目中引入Guava相关包
http://mvnrepository.com/artifact/com.google.guava/guava/21.0
maven项目
com.google.guava guava 21.0
gradle项目
//https://mvnrepository.com/artifact/com.google.guava/guava compilegroup:'com.google.guava',name:'guava',version:'21.0'
写一个SpringMVC的拦截器
SmoothBurstyInterceptor.java
importcom.google.common.util.concurrent.RateLimiter; importorg.springframework.web.servlet.ModelAndView; importorg.springframework.web.servlet.handler.HandlerInterceptorAdapter; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjava.util.concurrent.TimeUnit; publicclassSmoothBurstyInterceptorextendsHandlerInterceptorAdapter{ publicenumLimitType{ DROP,//丢弃 WAIT//等待 } /** *限流器 */ privateRateLimiterlimiter; /** *限流方式 */ privateLimitTypelimitType=LimitType.DROP; publicSmoothBurstyInterceptor(){ this.limiter=RateLimiter.create(10); } /** *@paramtps限流量(每秒处理量) *@paramlimitType限流类型:等待/丢弃(达到限流量) */ publicSmoothBurstyInterceptor(inttps,SmoothBurstyInterceptor.LimitTypelimitType){ this.limiter=RateLimiter.create(tps); this.limitType=limitType; } /** *@parampermitsPerSecond每秒新增的令牌数 *@paramlimitType限流类型:等待/丢弃(达到限流量) */ publicSmoothBurstyInterceptor(doublepermitsPerSecond,SmoothBurstyInterceptor.LimitTypelimitType){ this.limiter=RateLimiter.create(permitsPerSecond,1000,TimeUnit.MILLISECONDS); this.limitType=limitType; } @Override publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler)throwsException{ if(limitType.equals(LimitType.DROP)){ if(limiter.tryAcquire()){ returnsuper.preHandle(request,response,handler); } }else{ limiter.acquire(); returnsuper.preHandle(request,response,handler); } thrownewException("网络异常!");//达到限流后,往页面提示的错误信息。 } @Override publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,ModelAndViewmodelAndView)throwsException{ super.postHandle(request,response,handler,modelAndView); } @Override publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex)throwsException{ super.afterCompletion(request,response,handler,ex); } publicRateLimitergetLimiter(){ returnlimiter; } publicvoidsetLimiter(RateLimiterlimiter){ this.limiter=limiter; } }
SpringMVC拦截配置
WebConfig.java
@Component publicclassWebConfigextendsWebMvcConfigurerAdapter{ @Override publicvoidaddInterceptors(InterceptorRegistryregistry){ //多个拦截器组成一个拦截器链 registry.addInterceptor(newSmoothBurstyInterceptor(100,SmoothBurstyInterceptor.LimitType.DROP)).addPathPatterns("/**"); //限流可配置为SmoothBurstyInterceptor.LimitType.DROP丢弃请求或者SmoothBurstyInterceptor.LimitType.WAIT等待,100为每秒的速率 super.addInterceptors(registry); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。