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 接口訪問頻率限制內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: