您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在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 接口的訪問頻率,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。