SpringBoot使用RateLimiter通过AOP方式进行限流

1、引入依赖



	 com.google.guava
	 guava
	 25.1-jre

2、自定义注解

@Target({ElementType.PARAMETER, ElementType.METHOD})    
@Retention(RetentionPolicy.RUNTIME)    
@Documented    
public  @interface ServiceLimit { 
	 String description()  default "";
}

3、AOP实现类

@Component
@Scope
@Aspect
public class LimitAspect {
	////每秒只发出5个令牌,此处是单进程服务的限流,内部采用令牌捅算法实现
	private static   RateLimiter rateLimiter = RateLimiter.create(5.0);
	
	//Service层切点  限流
	@Pointcut("@annotation(com.itstyle.seckill.common.aop.ServiceLimit)")  
	public void ServiceAspect() {
		
	}
	
    @Around("ServiceAspect()")
    public  Object around(ProceedingJoinPoint joinPoint) { 
    	Boolean flag = rateLimiter.tryAcquire();
    	Object obj = null;
		try {
			if(flag){
				obj = joinPoint.proceed();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} 
    	return obj;
    } 
}

4、使用

        @Override
	@ServiceLimit
	@Transactional
	public Result startSeckil(long seckillId,long userId) {
		//todo 操作
	}

你可能感兴趣的:(AOP,SpringBoot)