自定义注解UserMultiSubmitLimit
package com.conf.annotation;
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 UserMultiSubmitLimit {
/**
* 指定时间内不可重复提交,单位毫秒,默认1秒
*/
long timeout() default 1000;
}
package com.conf.annotation.impl;
import com.conf.annotation.UserMultiSubmitLimit;
import com.controller.global.MyException;
import com.utils.RedisUtil;
import com.utils.RequestHolder;
import com.utils.StringUtils;
import com.utils.userUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;
@Aspect
@Component
@Slf4j
public class UserMultiSubmitAspect {
@Autowired
private RedisUtil redisUtil;
/**
* 是否存在注解,如果存在就获取
*/
private UserMultiSubmitLimit getAnnotationLog(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
if (method != null) {
return method.getAnnotation(UserMultiSubmitLimit.class);
}
return null;
}
/**
* @param point
*/
@Around("@annotation(com.conf.annotation.UserMultiSubmitLimit)")
public Object around(ProceedingJoinPoint point) throws Throwable {
//获取注解
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
UserMultiSubmitLimit avoidRepeatableCommit = getAnnotationLog(point);
HttpServletRequest request = RequestHolder.getHttpServletRequest();
String ip = userUtils.getIpAddr(request);
//目标类、方法
String className = method.getDeclaringClass().getName();
String name = method.getName();
// 得到类名和方法
String ipKey = String.format("%s#%s", className, name);
// 转换成HashCode
int hashCode = Math.abs(ipKey.hashCode());
String key = String.format("%s:%s_%d", "AVOID_REPEATABLE_COMMIT", ip, hashCode);
log.info("ipKey={},hashCode={},key={}", ipKey, hashCode, key);
long timeout = avoidRepeatableCommit.timeout();
String value = redisUtil.get(key);
if (StringUtils.isNotBlank(value)) {
log.info("请勿重复提交表单");
throw new MyException(105, "请勿重复提交表单");
}
// 设置过期时间
redisUtil.setEx(key, StringUtils.getUUID(), timeout, TimeUnit.MILLISECONDS);
//执行方法
Object object = point.proceed();
return object;
}
}
这个demo只针对用户访问的插入数据库的接口,管理员审核类可以用表的主键id作为key,这样就解决可以限制一条记录被多个人审核的问题。