常见限流方法总结

基于guava的令牌桶限流法

# 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Inherited
@Documented
public @interface ServiceLimit {
    String value() default "";
}

# 自定义切面
@Aspect
@Component
@Scope
@Data
@Slf4j
public class LimitAspect {
//每秒往桶中放1个key
    private static RateLimiter rateLimiter=RateLimiter.create(1);
    @Pointcut("@annotation(springboot.privateDemo.annotation.ServiceLimit)")
    public void serviceAspect(){

    }

    @Around("serviceAspect()")
    public Object serviceAround(ProceedingJoinPoint joinPoint){
        Boolean flag=rateLimiter.tryAcquire();
        Object result=null;
        if (flag){
            try {
               result= joinPoint.proceed();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
        return result;
    }
}

# controller
@RestController
public class LimitController {
    @GetMapping("/index")
    @ServiceLimit
    public String login(String name) {
        return "login in: " + name;
    }
}

【参考博客】
1.https://mp.weixin.qq.com/s/Jgp4KCRmuqVp6W6nd3Bxtw

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,637评论 25 708
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 12,993评论 2 59
  • 聊聊高并发系统限流特技-1来自开涛的博客 在开发高并发系统时有三把利器用来保护系统:缓存、降级和限流。缓存的目的是...
    meng_philip123阅读 6,695评论 1 20
  • 摘要:在开发高并发系统时有三把利器用来保护系统:缓存、降级和限流。而有些场景并不能用缓存和降级来解决,因此需有一种...
    落羽成霜丶阅读 2,184评论 0 18
  • 暮云收野色, 林影入平湖。 溽热幽中匿, 清凉水上凫。 (平水韵,第七部,虞)
    凿冰而钓阅读 2,108评论 41 76