因为业务需要后端做表单重复验证 故记录一下
1.创建注解类
/**
* 防重复注解
* @Author: lpc
* @since 2021-03-22
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface NoRepeatSubmit {
//指定时间内不可重复提交,单位毫秒
long timeout() default 1000*5;
}
2.具体处理
/**
* 定义切点
*
* @param point
*/
//环绕增强
@Around("execution(public * *(..)) && @annotation(com.quanyou.qup.retail.comm.aspect.NoRepeatSubmit)")
public Object interceptor(ProceedingJoinPoint point) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String ipAddr = getIpAddr(request);
//获取注解
MethodSignature signature = (MethodSignature) point.getSignature();
Method method = signature.getMethod();
//目标类、方法
String className = method.getDeclaringClass().getName();
String name = method.getName();
String ipKey = String.format("%s#%s", className, name);
int hashCode = Math.abs(ipKey.hashCode());
String key = String.format("%s_%d", ipAddr, hashCode);
log.info("ipKey={},hashCode={},key={}", ipKey, hashCode, key);
NoRepeatSubmit avoidRepeatableCommit = method.getAnnotation(NoRepeatSubmit.class);
long timeout = avoidRepeatableCommit.timeout();
if (timeout < 0) {
//过期时间30秒
timeout = 1000 * 30;
}
String value = (String) redisTemplate.opsForValue().get(key);
if (StringUtils.isNotBlank(value)) {
System.out.println("请勿重复提交");
return ResponseEntity.error("请勿重复提交");
}
redisTemplate.opsForValue().set(key, UUID.randomUUID(), timeout, TimeUnit.MILLISECONDS);
//执行方法
Object object = point.proceed();
return object;
}
/**
* 获取ip
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}