欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringCloud+Redis實(shí)現(xiàn)Api接口限流防止惡意刷接口

 更新時(shí)間:2024年03月07日 15:19:38   作者:12程序猿  
接口限流是為了保護(hù)系統(tǒng)和服務(wù),防止因?yàn)檫^多的請求而崩潰,本文主要介紹了SpringCloud+Redis實(shí)現(xiàn)Api接口限流防止惡意刷接口,具有一定的參考價(jià)值,感興趣的可以了解一下

一、API接口防刷

顧名思義,想讓某個(gè)接口某個(gè)人在某段時(shí)間內(nèi)只能請求N次。

二、原理

在請求的時(shí)候,服務(wù)器通過Redis記錄你請求的次數(shù),如果次數(shù)超過限制就不給訪問。
在redis保存的key是有失效的,過期就會(huì)刪除。

三、api限流的場景

限流的需求出現(xiàn)在許多常見的場景中:

  • 秒殺活動(dòng),有人使用軟件惡意刷單搶貨,需要限流防止機(jī)器參與活動(dòng)
  • 某api被各式各樣系統(tǒng)廣泛調(diào)用,嚴(yán)重消耗網(wǎng)絡(luò)、內(nèi)存等資源,需要合理限流
  • 淘寶獲取ip所在城市接口、微信公眾號識別微信用戶等開發(fā)接口,免費(fèi)提供給用戶時(shí)需要限流,更具有實(shí)時(shí)性和準(zhǔn)確性的接口需要付費(fèi)。

四、api限流代碼實(shí)現(xiàn)

使用自定義注解的方式實(shí)現(xiàn)

1.添加依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-bootstrap</artifactId>
   <version>3.1.5</version>
</dependency>
<!--nacos 服務(wù)注冊中心-->
<dependency>
   <groupId>com.alibaba.cloud</groupId>
   <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
   <version>2021.1</version>
</dependency>
<!--nacos 配置中心-->
<dependency>
   <groupId>com.alibaba.cloud</groupId>
   <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
   <version>2021.1</version>
</dependency>
<!--redis 依賴-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.添加自定義AccessLimit注解

package com.example.demo.aop;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定義接口:api接口限流
 * @author qzz
 * @date 2024/1/11
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AccessLimit {
    /**
     * 時(shí)間間隔(單位秒)
     * @return
     */
    int seconds() default 60;

    /**
     * 最大訪問次數(shù)
     * @return
     */
    int maxCount() default 60;

    /**
     * 是否需要登錄
     * @return
     */
    boolean needLogin() default true;
}

3.添加AccessLimitIntercepter攔截器

自定義一個(gè)攔截器,請求之前,進(jìn)行請求次數(shù)校驗(yàn)

package com.example.demo.intercepter;

import com.alibaba.fastjson.JSON;
import com.example.demo.aop.AccessLimit;
import com.example.demo.enums.CodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * 限制訪問攔截器
 * @author qzz
 * @date 2024/1/12
 */
@Slf4j
@Component
public class AccessLimitIntercepter implements HandlerInterceptor {
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    public AccessLimitIntercepter(RedisTemplate<String,Object> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //方法請求攔截    Handler 是否為 HandlerMethod 實(shí)例
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;

            // 獲取方法
            Method method = hm.getMethod();
            // 是否有AccessLimit注解
            if (!method.isAnnotationPresent(AccessLimit.class)) {
                return true;
            }
            //獲取方法中的AccessLimit注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null){
                return true;
            }
            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();
            String key=request.getRequestURI();
            //判斷是否登錄
            if(needLogin){
                //獲取登錄的session進(jìn)行判斷
                //...
                //獲取用戶id
                Long userId = 1L;
                key+=userId;
            }
            //從redis中獲取用戶訪問的次數(shù)
            Object count = redisTemplate.opsForValue().get(key);
            log.info("count:{}",count);
            if(count == null){
                //第一次訪問
                redisTemplate.opsForValue().set(key,1, Long.valueOf(String.valueOf(seconds)), TimeUnit.SECONDS);
                log.info("--------------------------第一次訪問--------------------------");
            }else if(count!=null && Integer.valueOf(String.valueOf(count)) < maxCount){
                //次數(shù)自增
                redisTemplate.opsForValue().increment(key,1);
                log.info("--------------------------次數(shù)自增--------------------------");
            }else{
                //超出訪問次數(shù)
                render(response, CodeMsg.ACCESS_LIMIT_REACHED);
                return false;
            }
        }
        return true;
    }

    private void render(HttpServletResponse response, CodeMsg codeMsg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        OutputStream outputStream = response.getOutputStream();
        String str = JSON.toJSONString(codeMsg);
        outputStream.write(str.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}

攔截器寫好了,但是還得添加注冊

4.WebConfig配置類

如果是Springboot的版本是2.*,只需要實(shí)現(xiàn)WebMvcConfigurer,然后重寫addInterceptors()方法,添加自定義攔截器即可。

如果是Springboot的版本是1.*,只需要實(shí)現(xiàn)WebMvcConfigurerAdapter,然后重寫addInterceptors()方法,添加自定義攔截器即可。

我的版本是2.4.6,所以代碼如下:

package com.example.demo.config;

import com.example.demo.intercepter.AccessLimitIntercepter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author qzz
 * @date 2024/1/12
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private AccessLimitIntercepter accessLimitIntercepter;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //添加攔截器
        registry.addInterceptor(accessLimitIntercepter);
    }
}

5.controller控制層測試接口

使用方式:在方法上使用注解@AccessLimit(seconds = 5, maxCount = 5, needLogin = true)

默認(rèn)5秒內(nèi),每個(gè)接口只能請求5次

package com.example.demo.controller;

import com.example.demo.aop.AccessLimit;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 攔截器注冊
 * @author qzz
 * @date 2024/1/11
 */
@RestController
public class TestController {

    @AccessLimit(seconds = 5, maxCount = 5, needLogin = true)
    @RequestMapping("test/api/limit")
    public String testApiLimit(){
        return "test api limit";
    }
}

五、完整代碼

代碼點(diǎn)擊此處下載

到此這篇關(guān)于SpringCloud+Redis實(shí)現(xiàn)Api接口限流防止惡意刷接口的文章就介紹到這了,更多相關(guān)SpringCloud Redis Api接口限流內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • ElasticSearch學(xué)習(xí)之多條件組合查詢驗(yàn)證及示例分析

    ElasticSearch學(xué)習(xí)之多條件組合查詢驗(yàn)證及示例分析

    這篇文章主要為大家介紹了ElasticSearch 多條件組合查詢驗(yàn)證及示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-02-02
  • 解決SpringMVC @RequestMapping不設(shè)置value出現(xiàn)的問題

    解決SpringMVC @RequestMapping不設(shè)置value出現(xiàn)的問題

    這篇文章主要介紹了解決SpringMVC @RequestMapping不設(shè)置value出現(xiàn)的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java實(shí)現(xiàn)多線程斷點(diǎn)下載

    Java實(shí)現(xiàn)多線程斷點(diǎn)下載

    這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)多線程斷點(diǎn)下載的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-03-03
  • SpringCloud Eureka Provider及Consumer的實(shí)現(xiàn)

    SpringCloud Eureka Provider及Consumer的實(shí)現(xiàn)

    這篇文章主要介紹了SpringCloud Eureka 提供者及調(diào)用者的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • java 裝飾模式(Decorator Pattern)詳解

    java 裝飾模式(Decorator Pattern)詳解

    這篇文章主要介紹了java 裝飾模式(Decorator Pattern)詳解的相關(guān)資料,需要的朋友可以參考下
    2016-10-10
  • java實(shí)現(xiàn)簡易撲克牌游戲

    java實(shí)現(xiàn)簡易撲克牌游戲

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)簡易撲克牌游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • 1秒實(shí)現(xiàn)Springboot 圖片添加水印功能

    1秒實(shí)現(xiàn)Springboot 圖片添加水印功能

    這篇文章主要介紹了1秒實(shí)現(xiàn)Springboot 圖片添加水印功能,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-12-12
  • springboot批量接收對象參數(shù),接收List方式

    springboot批量接收對象參數(shù),接收List方式

    在Spring Boot項(xiàng)目中,批量接收對象參數(shù)可以通過自定義對象和使用`@RequestBody`注解來實(shí)現(xiàn),首先,定義一個(gè)包含列表的自定義對象,然后在Controller中使用該對象接收前端傳遞的JSON數(shù)組,通過Postman模擬請求,可以成功批量接收并處理對象參數(shù)
    2025-02-02
  • Hibernate雙向一對一映射關(guān)系配置代碼實(shí)例

    Hibernate雙向一對一映射關(guān)系配置代碼實(shí)例

    這篇文章主要介紹了Hibernate雙向一對一映射關(guān)系配置代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • springcloud pom.xml完整配置詳解

    springcloud pom.xml完整配置詳解

    這篇文章主要介紹了springcloud pom.xml完整配置,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12

最新評論