- 首先创建自定义注解:主要用来标注在方法上。
importjava.lang.annotation.*;@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic@interfaceRepeatCommit{//重复提交的方法名StringmethodName();//是否开启重复提交检测booleanenable()defaulttrue;//多少秒内算重复提交,默认3s提交多次算重复提交intlimit()default3;}
- 创建切面类。
importcom.otitan.auth.framework.basepro.common.AuthCommon;importcom.otitan.sd.forest.baseinfo.annotation.RepeatCommit;importcom.otitan.webapp.framework.basepro.exception.BusinessException;importlombok.extern.slf4j.Slf4j;importorg.aspectj.lang.JoinPoint;importorg.aspectj.lang.annotation.Aspect;importorg.aspectj.lang.annotation.Before;importorg.aspectj.lang.annotation.Pointcut;importorg.aspectj.lang.reflect.MethodSignature;importorg.springframework.core.annotation.Order;importorg.springframework.data.redis.core.RedisTemplate;importorg.springframework.stereotype.Component;importjavax.annotation.Resource;importjava.util.concurrent.TimeUnit;/**
* 防止重复提交切面类
*/@Order(2)@Aspect@Component@Slf4jpublicclassRepeatCommitAspect{@ResourceprivateRedisTemplate redisTemplate;@ResourceAuthCommon authCommon;@Pointcut("@annotation(com.otitan.sd.forest.baseinfo.annotation.RepeatCommit)")publicvoidpointCut(){}@Before(value="pointCut()")publicvoidrepeatCommitCheck(JoinPoint joinPoint){//获取当前请求的userIdString userId= authCommon.getLoginUserInfo().getString("id");//获取当前注解MethodSignature signature=(MethodSignature) joinPoint.getSignature();RepeatCommit repeatCommit= signature.getMethod().getAnnotation(RepeatCommit.class);//获取注解每个参数值,用来实现放重复提交逻辑boolean enable= repeatCommit.enable();if(enable){String methodName= repeatCommit.methodName();int limit= repeatCommit.limit();String key= userId+ methodName;if(redisTemplate.opsForValue().get(key)!=null){thrownewBusinessException("请勿点击过快");}else{
redisTemplate.opsForValue().set(key, userId, limit,TimeUnit.SECONDS);}}}}
3.controller层方法上直接标注注解