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

2022-07-26,,,,

说明

我们在把开发好的网站上线之前一定要考虑到别人恶意刷新你的网页这种情况,最大限度的去限制他们。否则往往这将搞垮你的应用服务器,想象一下某个恶意用户利用众多肉鸡在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 防止恶意刷新内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《springboot结合ehcache防止恶意刷新请求的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。