java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot redis 接口访问频率限制

spring boot+ redis 接口访问频率限制的实现

作者:毅大师

这篇文章主要介绍了spring boot+ redis 接口访问频率限制的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

生产环境下可以解决的问题:

  1.短信验证码请求评率限制(防止抓包短信轰炸)

  2.热点数据请求评率限制(防止数据库爆炸)

@Component
public class BlackInterceper implements HandlerInterceptor {
 
 @Autowired
 private RedisTemplate<String, Object> redisTemplate;
 
 private Logger log = LoggerFactory.getLogger(this.getClass());
 
 @Override
 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
  throws Exception {
 response.setHeader("Content-type", "text/html;charset=UTF-8");
 String token = request.getHeader(Cons.TOKEN.WECHAT);
 String requestURI = request.getRequestURI();
 
 if (StringUtils.isBlank(token)) {
  response.setHeader("Content-type", "text/html;charset=UTF-8");
  response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(401, "未授权")));
  return false;
 }
 Integer userId = (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, "由于存在恶意攻击你已被限制访问")));
  return false;
  }
 }
 Integer count = (Integer)redisTemplate.opsForValue().get("limit:"+token);
 if(count==null){
  redisTemplate.opsForValue().set("limit:"+token, 1, 60, TimeUnit.SECONDS);
  return true;
 }else{
  if(count>100 && count<150){
  response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(500, "请求太频繁,请稍后再试")));
  redisTemplate.opsForValue().increment("limit:"+token, 1);
  return false;
  }else if(count>=150){
  redisTemplate.opsForSet().add("black",userId,2,TimeUnit.DAYS);
  response.getWriter().write(JsonUtils.marshalToString(ReturnResult.build(500, "请求太频繁,已经被限制访问")));
 
  //redisTemplate.opsForSet().add("black",token);
  return false;
  }else{
  redisTemplate.opsForValue().increment("limit:"+token, 1);
  return true;
  }
 }
 }
 
 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
  ModelAndView modelAndView) throws Exception {
 // TODO Auto-generated method stub
 
 }
 
 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
  throws Exception {
 // TODO Auto-generated method stub
 
 }
}

到此这篇关于spring boot+ redis 接口访问频率限制的实现的文章就介绍到这了,更多相关springboot redis 接口访问频率限制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文