在項目中使用(guava的RateLimiter)基於自定義註解方式實現 實戰限流

1、單體項目可以使用這種方式實現限流,而分佈式和集羣項目是 基於基於Redis+Lua的分佈式限流

常用的限流算法有漏桶算法和令牌桶算法,guava的RateLimiter使用的是令牌桶算法,也就是以固定的頻率向桶中放入令牌,例如一秒鐘10枚令牌,實際業務在每次響應請求之前都從桶中獲取令牌,只有取到令牌的請求才會被成功響應,獲取的方式有兩種:阻塞等待令牌或者取不到立即返回失敗,下圖來自網上:

這裏寫圖片描述

本次實戰,我們用的是guava的RateLimiter,場景是spring mvc在處理請求時候,從桶中申請令牌,申請到了就成功響應,申請不到時直接返回失敗;

這是一個maven工程,所以首先我們在pom中把guava的依賴添加進來:

<!--限流引入的jar-->
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>27.1-jre</version>
</dependency>

1、自定義註解限流類如下:

import java.lang.annotation.*;

@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomRateLimiter {

    //往令牌桶放入令牌的速率
    double rate();
    //獲取令牌的超時時間
    long timeOut() default 0;
}

2、自定義切面類 RateLimiterAspect類 ,修改掃描自己controller類

import com.google.common.util.concurrent.RateLimiter;
import com.imooc.annotation.CustomRateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class RateLimiterAspect {
    @Autowired
    private HttpServletResponse response;

    //創建了一個令牌桶限流算法的限流器, 方便測試創建每秒創建2桶
    private RateLimiter rateLimiter = RateLimiter.create(2);

    public final static Logger log = LoggerFactory.getLogger(RateLimiterAspect.class);

    @Pointcut("execution( public * com.zz.controller.*.*(..))")
    public void pointcut(){

    }
    @Around("pointcut()")
    public Object process(ProceedingJoinPoint proceedingJoinPoint) throws  Throwable {
        MethodSignature  signature = (MethodSignature)proceedingJoinPoint.getSignature();
        //使用Java 反射技術獲取方法上是否有@CustomRateLimiter 註解類
        CustomRateLimiter geelyRateLimiter = signature.getMethod().getDeclaredAnnotation(CustomRateLimiter.class);
        if(geelyRateLimiter == null){
            //正常執行方法,執行正常業務邏輯
            return proceedingJoinPoint.proceed();
        }
        //獲取註解上的參數,獲取配置的速率
        double rate = geelyRateLimiter.rate();
        //獲取註解上的參數,獲取等待令牌等待時間
        long timeOut = geelyRateLimiter.timeOut();
        // 設置限流速率
        rateLimiter.setRate(rate);
        boolean tryAcquire = rateLimiter.tryAcquire(500, TimeUnit.MILLISECONDS);
        if(!tryAcquire){
            //服務降級
            fullback();
            return null;

        }
        // 獲取到令牌,直接放行
        return proceedingJoinPoint.proceed();
    }



    private  void  fullback(){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = null;
        try {
            writer= response.getWriter();
            JSONObject o = new JSONObject();
            // 自定義返回默認值 , 狀態碼可以根據自己系統設status :我這邊默認是500錯誤
            o.put("status",500);
            o.put("msg","請求太頻繁,請稍後重試!");
            o.put("data",null);
            writer.printf(o.toString()
            );

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(writer != null){
                writer.close();
            }
        }
    }
}

3、在需要限流的類添加註解: test 改接口是沒有用切面方式,有代碼入侵,基於註解的test1是沒有代碼入侵。

import java.util.concurrent.TimeUnit;
@RestController
@Api(value = "限流", tags = {"限流測試接口"})
@RequestMapping("limiter")
public class LimiterController {

    //表示桶容量爲5,且每秒新增5個令牌 。1秒等於1000毫秒 表示:200毫秒放一個令牌
    RateLimiter limiter = RateLimiter.create(2);

    @ApiOperation(value = "限流測試接口",notes = "限流測試接口", httpMethod = "GET")
    @GetMapping("/test")
    public CustomJSONResult test(){
        //1.限流處理,客戶端請求從桶中獲取令牌,如果在500毫秒內沒有獲取到令牌,則直接走服務降級處理
        boolean tryAcquire = limiter.tryAcquire(500, TimeUnit.MILLISECONDS);
        if(!tryAcquire){
            return CustomJSONResult.errorMsg("請求太頻繁,請稍後重試!");
        }
        return IMOOCJSONResult.ok();
    }


    @ApiOperation(value = "自定義限流注解測試接口",notes = "自定義限流注解測試接口", httpMethod = "GET")
    @CustomRateLimiter(rate = 1.0,timeOut = 500)
    @GetMapping("/test2")
    public CustomJSONResult test2(){
        System.out.println("正常執行業務邏輯");
        return CustomJSONResult.ok();
    }

}

4、使用 jmeter測試接口;這樣就達到限流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章