软件编程
位置:首页>> 软件编程>> java编程>> springboot 防止重复请求防止重复点击的操作

springboot 防止重复请求防止重复点击的操作

作者:低端程序狗  发布时间:2021-09-19 16:03:00 

标签:springboot,重复,请求,点击

  利用 springboot + redis 实现过滤重复提交的请求,业务流程如下所示,首先定义一个 * ,拦截需要进行过滤的URL,然后用 session + URL 作为唯一 key,利用 redis setnx 命令,来判断请求是否重复,如果 key set 成功,说明非重复请求,失败则说明重复请求;

springboot 防止重复请求防止重复点击的操作

  URL * 可以使用 spring * ,但使用 spring,每个需要过滤的新 URL 都需要添加配置,因此这里使用 AOP 注解 的形式来实现,这样更直观一点;
  首先,定义注解:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface AvoidRepeatRequest {
   /** 请求间隔时间,单位秒,该时间范围内的请求为重复请求 */
   int intervalTime() default 5;
   /** 返回的提示信息 */
   String msg() default "请不要频繁重复请求!";
}

  然后定义 AOP,实现重复请求过滤功能:

@Component
@Aspect
@Order(100)
public class FilterRepeatRequest {
   private static final String SUFFIX = "REQUEST_";
   @Autowired
   private RedisTemplate redisTemplate;

// 定义 注解 类型的切点
   @Pointcut("@annotation(com.common.ann.AvoidRepeatRequest)")
   public void arrPointcut() {}

// 实现过滤重复请求功能
   @Around("arrPointcut()")
   public Object arrBusiness(ProceedingJoinPoint joinPoint) {
       // 获取 redis key,由 session ID 和 请求URI 构成
       ServletRequestAttributes sra = (ServletRequestAttributes)
       RequestContextHolder.currentRequestAttributes();
       HttpServletRequest request = sra.getRequest();
       String key = SUFFIX + request.getSession().getId() + "_" + request.getRequestURI();

// 获取方法的 AvoidRepeatRequest 注解
       Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
       AvoidRepeatRequest arr = method.getAnnotation(AvoidRepeatRequest.class);

// 判断是否是重复的请求
       if (!redisTemplate.opsForValue().setIfAbsent(key, 1, arr.intervalTime(), TimeUnit.SECONDS)) {
           // 已发起过请求
           System.out.println("重复请求");
           return arr.msg();
       }

try {
           // 非重复请求,执行业务代码
           return joinPoint.proceed();
       } catch (Throwable throwable) {
           throwable.printStackTrace();
           return "error";
       }
   }
}

  测试使用:

@RestController
public class TestAop {

// 使用 AvoidRepeatRequest 注解的请求,表明需要进行重复请求判断
   @AvoidRepeatRequest(intervalTime = 6, msg = "慢点,兄弟")
   @GetMapping("test/aop")
   public String test() {
       return "test aop";
   }
}

来源:https://blog.csdn.net/qq_36845919/article/details/114295549

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com