SpringBootはRateLimiterを用いてAOP方式で限流を行う

1212 ワード

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   
	}