常见限流方法总结

基于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

你可能感兴趣的:(常见限流方法总结)