• 利用拦截器加缓存完成接口防刷操作


    One person walks fast, but a group of people can go further

    为什么需要接口防刷

    为了减缓服务器压力,将服务器资源留待给有价值的请求,防止恶意访问,一般的程序都会有接口防刷设置,接下来介绍一种简单灵活的接口防刷操作

    技术解析

    主要采用的技术还是拦截+缓存,我们可以通过自定义注解,将需要防刷的接口给标记出来管理,利用缓存统计指定时间区间里,具体的某个ip访问某个接口的频率,如果超过某个阈值,就让他进一会儿小黑屋,到期自动解放

    主要代码

    • 前置环境搭建,Spring Boot项目,引入Web和Redis依赖

      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.3.3.RELEASE</version>
      </parent>
      
      <dependencies>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
      	</dependency>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-data-redis</artifactId>
          </dependency>
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter</artifactId>
          </dependency>
          <dependency>
      </dependencies>
      
    • 自定义注解

      image-20220216122645892

    • 定义拦截器,重写preHandler方法

      @Override
      	public boolean preHandle(HttpServletRequest request ,HttpServletResponse response ,Object handler) throws Exception {
      		
              log.info("------------接口防刷拦截器---------------");
      
              if (handler instanceof HandlerMethod) {
      
                  HandlerMethod handlerMethod = (HandlerMethod) handler;
      
                  AccessLimit accessLimit = handlerMethod.getMethodAnnotation(AccessLimit.class);
                  // 如果没有该注解,则不在防刷目标里,直接返回
                  if (accessLimit == null) {
                      return true;
                  }
                  // 获取最大访问次数
                  int maxAccessCnt = accessLimit.maxAccessCnt();
                  // 获取ip
                  String key = getRealIp(request);
                  // ip+请求的接口路径 => 唯一标识key
                  key += request.getRequestURI();
      
                  //当前访问次数
                  Object value = redisTemplate.opsForValue().get(key);
      
                  if (value == null) {
                      //第一次访问 设置key保留时长为1s
                      redisTemplate.opsForValue().set(key, 1, 1L, TimeUnit.SECONDS);
                  } else {
      
                      Integer currentCnt = (Integer) value;
      
                      if (currentCnt < maxAccessCnt) {
                          //对应key值自增
                          redisTemplate.opsForValue().increment(key);
                      } else {
                          //超出接口时间段内允许访问的次数,直接返回错误信息,同时设置过期时间 20s自动剔除
                          redisTemplate.expire(key, 20L,TimeUnit.SECONDS);
                          response.setContentType("application/json;charset=utf-8");
                          try {
                              OutputStream out = response.getOutputStream();
                              out.write("访问次数已达上线!请稍后再访问".getBytes(StandardCharsets.UTF_8));
                              out.flush();
                              out.close();
                          } catch (IOException e) {
                              e.printStackTrace();
                          }
                          return false;
                      }
                  }
      
      
              }
              return true;
          }
      
    • 添加到需要防刷的接口上

      /**
       * 返回不携带data的(成功例子)
       * @return
       */
      @AccessLimit
      @GetMapping("/getPaperS")
      public ApiResult getPaperInfoSuccess() {
         if (log.isInfoEnabled()) {
            log.info("收到获取paper信息请求...");
         }
         //...业务逻辑
         if (log.isInfoEnabled()) {
            log.info("完成获取paper信息请求,准备返回对象信息");
         }
         return ApiResultGenerator.success();
      }
      

    测试结果

    正常情况下

    image-20220216134636625

    到底时间段内最大访问次数时

    image-20220216134725165

  • 相关阅读:
    lua的模块与类
    远程控制软件
    【C++】STL详解(九)—— set、map、multiset、multimap的介绍及使用
    ping no reply
    大数据计算里的加速利器-向量化
    docker中使用docker-compose搭建Elasticsearch 7.8.0集群及安装IK分词器
    【Linux】进程地址空间
    3D可视化工厂是如何实现的?
    SpringBoot整合MongoDB以及副本集、分片集群的搭建
    网络连接 CSP-J 2021 简单的模拟
  • 原文地址:https://www.cnblogs.com/iamamg97/p/15900251.html