利用攔截器加緩存完成接口防刷操作


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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM