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