- 首先创建自定义注解:主要用来标注在方法上。
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatCommit {
//重复提交的方法名
String methodName();
//是否开启重复提交检测
boolean enable() default true;
//多少秒内算重复提交,默认3s提交多次算重复提交
int limit() default 3;
}
- 创建切面类。
import com.otitan.auth.framework.basepro.common.AuthCommon;
import com.otitan.sd.forest.baseinfo.annotation.RepeatCommit;
import com.otitan.webapp.framework.basepro.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
/**
* 防止重复提交切面类
*/
@Order(2)
@Aspect
@Component
@Slf4j
public class RepeatCommitAspect {
@Resource
private RedisTemplate redisTemplate;
@Resource
AuthCommon authCommon;
@Pointcut("@annotation(com.otitan.sd.forest.baseinfo.annotation.RepeatCommit)")
public void pointCut() {
}
@Before(value = "pointCut()")
public void repeatCommitCheck(JoinPoint joinPoint) {
//获取当前请求的userId
String 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) {
throw new BusinessException("请勿点击过快");
} else {
redisTemplate.opsForValue().set(key, userId, limit, TimeUnit.SECONDS);
}
}
}
}
3.controller层方法上直接标注注解