1.导入POM依赖包
<!--Guava限流-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
2.配置自定义注解
@Inherited
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimitAnnotation {
}
3.使用aop方式扫描注解
package cn.sms.aop;
import cn.sms.core.security.Result;
import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import java.sql.Timestamp;
import java.util.Date;
@Aspect
@Component
public class RateLimitAop {
private RateLimiter rateLimiter= RateLimiter.create(1);
@Pointcut(value = "@annotation(cn.sms.aop.RateLimitAnnotation)")
public void rateLimit(){
}
@Around("rateLimit()")
public Result around() {
Boolean flag = rateLimiter.tryAcquire();
if (!flag) {
return Result.error(new Timestamp(new Date().getTime()).toString()+"限流");
}
return Result.success();
}
}
4.在controller层使用自定义注解
@RateLimitAnnotation