基于令牌桶算法实现的SpringBoot分布式无锁限流插件,支持方法级别、系统级别的限流,提供快速失败与CAS阻塞两种方案,开箱即用!更多功能更新中

 

简介

spring-boot-starter-current-limiting:完美嵌入SpringBoot应用的无锁限流插件,支持方法级别、系统级别限流,支持设置系统启动保护时间,提供快速失败与CAS阻塞两种限流方案,这些功能只需要导入依赖,简单配置即可使用。

15558483556461555848355646

 

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");
    }

}

需要注意的是,以上实现类在Application中只能注入一个。

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值