栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot结合ehcache防止恶意刷新请求的实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot结合ehcache防止恶意刷新请求的实现

说明

我们在把开发好的网站上线之前一定要考虑到别人恶意刷新你的网页这种情况,最大限度的去限制他们。否则往往这将搞垮你的应用服务器,想象一下某个恶意用户利用众多肉鸡在1分钟内请求你网页几十万次是个什么情形?
部分内容参考网络。

要达到什么效果?

我限制请求的用户,根据来访IP去记录它N分钟之内请求单一网页的次数,如果超过N次我就把这个IP添加到缓存黑名单并限制它3小时之内无法访问类型网页。

效果图

1分钟内请求单网页超过15次就被加入黑名单,冻结3小时!

开发步骤
  • 采用AOP+Ehcache方式。(Redis也可以)
  • AOP用于拦截和逻辑判断,Ehcache负责计数和缓存。

配置ehcache

略。

创建注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@documented
@Order(Ordered.HIGHEST_PRECEDENCE)
public @interface RequestLimit {
  
  int count() default 15;

  
  long time() default 1000*60;
}

创建AOP

@Aspect
@Component
public class RequestLimitAspect {
  private static final Logger logger = LoggerFactory.getLogger(RequestLimit.class);

  @Autowired
  EhcacheUtil ehcacheUtil;

  @Before("within(@org.springframework.stereotype.Controller *) && @annotation(limit)")
  public void requestLimit(final JoinPoint joinPoint , RequestLimit limit) throws RequestLimitException {
    try {
      Object[] args = joinPoint.getArgs();
      HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
      String ip = IpUtil.getRemoteIp(request);
      String uri = request.getRequestURI().toString();
      String key = "req_"+uri+"_"+ip;
      String blackKey = "black_"+ip; // 黑名单IP封锁一段时间
      int count = 0; // 访问次数
      // 判断是否在黑名单
      if (ehcacheUtil.contains("countcache",blackKey)){
 throw new RequestLimitException();
      }else{
 // 判断是否已存在访问计数
 if (!ehcacheUtil.contains("limitCache",key)) {
   ehcacheUtil.put("limitCache",key,1);

 } else {
   count = ehcacheUtil.getInt("limitCache",key)+1;
   ehcacheUtil.put("limitCache",key,count);
   if (count > limit.count()) {
     logger.info("用户IP[" + ip + "]访问地址[" + uri + "]超过了限定的次数[" + limit.count() + "]");
     // 加入黑名单
     ehcacheUtil.put("countcache",blackKey,"badguy");
     throw new RequestLimitException();
   }
 }
      }


    }catch (RequestLimitException e){
      throw e;
    }catch (Exception e){
      logger.error("发生异常",e);
    }
  }
}

应用aop

找到要应用的接口加上注解@RequestLimit即可。

 @RequestLimit(count=10)
  @OperLog(operModule = "更多文章",operType = "查询",operDesc = "查询更多文章")
  @GetMapping("/more/{categoryId}")
  public String getMore(@PathVariable("categoryId") String categoryId, Model model, HttpServletRequest request) {
    // 略
  }

到此这篇关于springboot结合ehcache防止恶意刷新请求的实现的文章就介绍到这了,更多相关springboot 防止恶意刷新内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/129819.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号