1. Import the POM dependency package
<!--Guava限流-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
2. Configure custom annotations
@Inherited
@Documented
@Target({
ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RateLimitAnnotation {
}
3. Use aop to scan annotations
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. Use custom annotations in the controller layer
@RateLimitAnnotation