避免重复提交注解
避免重复提交注解
①注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface AvoidRepeatableCommit { /** * 指定时间内不可重复提交,单位毫秒 * @return */ long timeout() default 100; }
② 实现方法
@Aspect
@Component
@Slf4j
public class AvoidRepeatableCommitAspect
{
@Resource
private RedisService redisService;
/**
* @param point
*/
@Around("@annotation(com.iktapp.skc.common.security.aspect.avoidrepeat.AvoidRepeatableCommit)")
public Object around(ProceedingJoinPoint point) throws Throwable {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
String ip = IPUtil.getIPAddress(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",ip,hashCode);
AvoidRepeatableCommit avoidRepeatableCommit = method.getAnnotation(AvoidRepeatableCommit.class);
long timeout = avoidRepeatableCommit.timeout();
if (timeout < 0){
//过期时间5秒
timeout = 5*1000;
}
String value = (String) redisService.getCacheObject(key);
if (StringUtils.isNotBlank(value)){
return AjaxResult.error("请勿重复提交");
}
redisService.setCacheObject(key, UUID.randomUUID().toString(),timeout, TimeUnit.MILLISECONDS);
//执行方法
Object object = point.proceed();
return object;
}
}

浙公网安备 33010602011771号