前言:在实际开发中,我们可能会遇到需要对某个接口请求频率做一定时间间隔的限制,如生活中常见的应用上二维码刷新频率限制等。于是这里做了一个简单的切面限制频率案例,使用的是切面注解方式,减少侵入性。
一、切面实现请求接口频率限制
1.pom.xml引入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
2.自定义一个注解
import java.lang.annotation.*;
/**
* 用于限制接口请求频率
*/
@Documented
@Target({
ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ReqLimit {
/**
* 请求频率限制(单位秒)默认3秒可自己调整
*/
int rateSecond() default 3;
}
3.创建一个@Aspect的切面类,用来处理核心逻辑
@Aspect
@Component
@Order(1)
public class ReqLimitAspect {
public static final String REQUEST_LIMIT = "requestLimit";
/**
* 频率限制切入点(注解类的路径)
*/
@Pointcut(value = "@annotation(com.alone.server.annotation.ReqLimit)")
public void reqLimitPointCut()