spring boot+ redis 接口访问频率限制的实现
生产环境下可以解决的问题:
1.短信验证码请求评率限制(防止抓包短信轰炸)
2.热点数据请求评率限制(防止数据库爆炸)
@Component publicclassBlackInterceperimplementsHandlerInterceptor{ @Autowired privateRedisTemplateredisTemplate; privateLoggerlog=LoggerFactory.getLogger(this.getClass()); @Override publicbooleanpreHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler) throwsException{ response.setHeader("Content-type","text/html;charset=UTF-8"); Stringtoken=request.getHeader(Cons.TOKEN.WECHAT); StringrequestURI=request.getRequestURI(); if(StringUtils.isBlank(token)){ response.setHeader("Content-type","text/html;charset=UTF-8"); response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(401,"未授权"))); returnfalse; } IntegeruserId=(Integer)redisTemplate.opsForValue().get(Cons.TOKEN.WECHAT+":"+token); log.error("userId={},访问了url={},请求ip={}",token,requestURI,IpUtil.getIpAddress(request)); if(redisTemplate.hasKey("black")){ if(redisTemplate.opsForSet().isMember("black",userId)){ response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(500,"由于存在恶意攻击你已被限制访问"))); returnfalse; } } Integercount=(Integer)redisTemplate.opsForValue().get("limit:"+token); if(count==null){ redisTemplate.opsForValue().set("limit:"+token,1,60,TimeUnit.SECONDS); returntrue; }else{ if(count>100&&count<150){ response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(500,"请求太频繁,请稍后再试"))); redisTemplate.opsForValue().increment("limit:"+token,1); returnfalse; }elseif(count>=150){ redisTemplate.opsForSet().add("black",userId,2,TimeUnit.DAYS); response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(500,"请求太频繁,已经被限制访问"))); //redisTemplate.opsForSet().add("black",token); returnfalse; }else{ redisTemplate.opsForValue().increment("limit:"+token,1); returntrue; } } } @Override publicvoidpostHandle(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler, ModelAndViewmodelAndView)throwsException{ //TODOAuto-generatedmethodstub } @Override publicvoidafterCompletion(HttpServletRequestrequest,HttpServletResponseresponse,Objecthandler,Exceptionex) throwsException{ //TODOAuto-generatedmethodstub } }
到此这篇关于springboot+redis接口访问频率限制的实现的文章就介绍到这了,更多相关springbootredis接口访问频率限制内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。