1. 程式人生 > >基於令牌桶算法實現的SpringBoot無鎖限流插件

基於令牌桶算法實現的SpringBoot無鎖限流插件

不可用 spec servlet shu cas 完美 foxmail 接口 RoCE

技術分享圖片

1.簡介

spring-boot-starter-current-limiting:完美嵌入SpringBoot應用的無鎖限流插件,支持方法級別、系統級別限流,支持設置系統啟動保護時間,提供快速失敗與CAS阻塞兩種限流方案,這些功能只需要導入依賴,簡單配置即可使用。

技術分享圖片

2.Maven

<dependency>
  <groupId>cn.yueshutong</groupId>
  <artifactId>spring-boot-starter-current-limiting</artifactId>
  <version>0.0.1.RELEASE</version>
</dependency>

3.方法限流

在需要限流的方法上使用 @CurrentLimiter 註解,示例代碼如下:

@RestController
public class MyController {

    @RequestMapping("/hello")
    @CurrentLimiter(QPS = 2)
    public String hello(){
        return "hello";
    }

}

@CurrentLimiter 註解參數說明:

屬性 說明 默認值
QPS 每秒並發量 20
initialDelay 初始延遲時間 0
failFast 開啟快速失敗 true

4.系統限流

對整個應用的限流只需要在配置文件中配置即可,示例代碼如下:

current.limiting.enabled=true
current.limiting.part-enabled=false
current.limiting.qps=100
current.limiting.fail-fast=true
current.limiting.initial-delay=0

參數說明:

屬性 說明 默認值
enabled 開啟全局限流 false
part-enabled 開啟註解限流 true
qps 每秒並發量 100
fail-fast 開啟快速失敗 true
initial-delay 初始延遲時間 0

5.拒絕策略

提供快速失敗與CAS阻塞兩種限流方案。如果是阻塞則不需要拒絕策略,當獲取到令牌後依舊會繼續執行,可以當做一種限制速率的措施。這裏只討論快速失敗的拒絕策略。

快速失敗的默認策略是統一返回“服務不可用”的英文說明文字,如果用戶需要自定義拒絕策略,提供兩種接口供實現。

針對被註解的方法進行自定義拒絕策略是實現CurrentAspectHandler接口,示例代碼:

@Component
public class MyAspectHandler implements CurrentAspectHandler {
    @Override
    public Object around(ProceedingJoinPoint pjp, CurrentLimiter rateLimiter) throws Throwable {
        //被註解修飾的方法返回值,慎用!
        //可以結合Controller返回自定義視圖
        return "fail";
    }
}

針對系統級別的拒絕策略是實現CurrentInterceptorHandler接口,示例代碼:

@Component
public class MyInterceptorHandler implements CurrentInterceptorHandler {
    @Override
    public void preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.getWriter().print("fail");
    }

}

6.關於作者

博客:http://www.yueshutong.cn

郵箱:[email protected]

Github:https://github.com/yueshutong/spring-boot-starter-current-limiting

Gitee:https://gitee.com/zyzpp/spring-boot-starter-current-limiting

交流QQ群:781927207

基於令牌桶算法實現的SpringBoot無鎖限流插件