专业的网站首页建设公司,公章电子版在线制作,纪念馆展厅设计,wordpress 缓慢说明#xff1a;实际开发中#xff0c;我们在前端页面上点击了一个按钮#xff0c;访问了一个接口#xff0c;这时因为网络波动或者其他原因#xff0c;页面上没有反应#xff0c;用户可能会在短时间内再次点击一次或者用户以为没有点到#xff0c;很快的又点了一次。导…说明实际开发中我们在前端页面上点击了一个按钮访问了一个接口这时因为网络波动或者其他原因页面上没有反应用户可能会在短时间内再次点击一次或者用户以为没有点到很快的又点了一次。导致短时间内发送了两个请求到后台可能会导致数据重复添加。
为了避免短时间内对一个接口访问我们可以通过AOP自定义注解Redis的方式在接口上加一个自定义注解然后通过AOP的前置通知在Redis中存入一个有效期的值当访问接口时这个值还未过期则抛出异常以此来避免短时间内对接口的方法。
实现
第一步创建一个自定义注解设置两个属性一个是key一个是这个key在Redis中的有效时间
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;/*** 自定义注解*/
Target(ElementType.METHOD)
Retention(RetentionPolicy.RUNTIME)
public interface LimitAccess {/*** 限制访问的key* return*/String key();/*** 限制访问时间* return*/int times();
}第二步创建对应的Aspect
import com.hezy.annotation.LimitAccess;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;/*** AOP类通知类*/
Component
Aspect
public class LimitAspect {Autowiredprivate RedisTemplate redisTemplate;Pointcut(annotation(com.hezy.annotation.LimitAccess))public void pt(){};Around(pt())public Object aopAround(ProceedingJoinPoint pjp) throws Throwable {// 获取切入点上面的自定义注解Signature signature pjp.getSignature();MethodSignature methodSignature (MethodSignature) signature;// 获取方法上面的注解LimitAccess limitAccess methodSignature.getMethod().getAnnotation(LimitAccess.class);// 获取注解上面的属性int limit limitAccess.times();String key limitAccess.key();// 根据key去找Redis中的值Object o redisTemplate.opsForValue().get(key);// 如果不存在说明是首次访问存入Redis过期时间为limitAccess中的timeif (o null) {redisTemplate.opsForValue().set(key, , limit, TimeUnit.SECONDS);// 执行切入点的方法return pjp.proceed();} else {// 如果存在说明不是首次访问抛出异常throw new RuntimeException(访问过于频繁);}}
}第三步在需要限制的接口上加上这个注解并设置key和限制访问时间如下这个这个接口设置key为set实际开发中可以设置一个随机值或者按照规则自定义设置times为限制访问时间 GetMapping(/limit)LimitAccess(key limit, times 10)public String limit() {return success;}演示
启动项目访问该接口
首次访问没得问题同时在Redis中存入值 短时间内连续访问因为Redis中值未过期 10秒之后再访问又可以了Redis中的值过期了 以上就是使用Redis实现接口防抖避免短时间内连续访问接口。实际开发中可以将异常设置为自定义异常。