当前位置:   article > 正文

防止重复提交 根据redis+springboot aop +注解实现_spring aop + redis 实现防重复提交注解

spring aop + redis 实现防重复提交注解
  1. /**
  2. * @Description 防止重复提交注解
  3. * @Author jinpk
  4. * @Date 2022/8/15 10:51
  5. */
  6. @Target(ElementType.METHOD)
  7. @Retention(RetentionPolicy.RUNTIME)
  8. public @interface NoRepeatSubmit {
  9. }
  1. /**
  2. * @Description 定义切面,实现拦截功能
  3. * @Author jinpk
  4. * @Date 2022/8/15 10:58
  5. */
  6. @Aspect
  7. @Component
  8. public class NoRepeatSubmitAspect {
  9. protected final Logger log = LoggerFactory.getLogger(this.getClass());
  10. @Autowired
  11. RedisTemplate redisTemplate;
  12. //临界值
  13. @Value("${redisConfig.criticality}")
  14. private Integer criticality;
  15. /**
  16. * 横切点
  17. */
  18. @Pointcut("@annotation(noRepeatSubmit)")
  19. public void repeatPoint(NoRepeatSubmit noRepeatSubmit) {
  20. }
  21. /**
  22. * 接收请求,并记录数据
  23. */
  24. @Around(value = "repeatPoint(noRepeatSubmit)")
  25. public Object doBefore(ProceedingJoinPoint joinPoint, NoRepeatSubmit noRepeatSubmit) {
  26. //参数
  27. Object[] args = joinPoint.getArgs();
  28. //参数转化成json
  29. String data = JsonUtils.objectToJson(args);
  30. //参数加密
  31. String key = MD5.stringToMD5(data);
  32. //方法名
  33. String methodName = joinPoint.getSignature().toShortString();
  34. log.info("进行防重复提交");
  35. try {
  36. // 如果缓存中有这个url视为重复提交
  37. if (redisTemplate.boundHashOps("repeat:key").get(key) == null) {
  38. //获取全部的key
  39. Set<String> keys = redisTemplate.boundHashOps("repeat:key").keys();
  40. if (!CollectionUtils.isEmpty(keys)){
  41. System.out.println("========redis:防止重复提交的key的数量=========:"+keys.size());
  42. //大于临界值时 redis repeat:key 此文件夹下所有数据清零
  43. if (keys.size() >= criticality){
  44. redisTemplate.delete("repeat:key");
  45. }
  46. }
  47. redisTemplate.boundHashOps("repeat:key").put(key, methodName);
  48. return joinPoint.proceed();
  49. }else {
  50. log.info("重复提交");
  51. return AjaxResult.error("请勿重复提交!");
  52. }
  53. } catch (Throwable throwable) {
  54. log.info("运行业务代码出错", throwable);
  55. return AjaxResult.error("请求异常请稍后!");
  56. }
  57. }
  58. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/550757
推荐阅读
相关标签
  

闽ICP备14008679号