实现方法
编写一个自定义注解和一个拦截器,本文中的自定义注解可以指定传入超时时间(默认是60秒),拦截器对使用注解的方法进行拦截,获取到传入的参数和超时时间,将传入的一个或多个参数拼接成一个json字符串,使用md5进行加密后把它作为key存入Redis缓存中,如果根据key在超时时间范围内能找到相同的内容,则返回表单内容已提交提示,否则继续执行方法。
自定义一个@Idempotent注解
/**
* 自定义防重复提交注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Idempotent {
/**可以传入指定的重复提交限定时间,默认60秒*/
long value() default 60000;
}
自定义一个IdempotentAspect拦截器
/**
* 拦截器
* @author 豆芽
* @Date 2020-11-11 15:05
*/
@Aspect
@Component
public class IdempotentAspect {
private Logger logger = LoggerFactory.getLogger(IdempotentAspect.class);
@Autowired
private RedisService redisService;
@Around("@annotation(idempotent)")
public Object aroundMethod(ProceedingJoinPoint pjp,Idempotent idempotent)throws Throwable{
/**获取执行方法的参数*/
Object[] args = pjp.getArgs();
/**获取注解传入的超时时间*/
long timeOut = idempotent.value();
/**使用MD5对传入的参数进行加密*/
String encode = getMd5Value(args);
try{
/** 校验是否重复提交过,如果没有,则按指定超时时间存入Redis缓存 */
boolean checkFormToken = redisService.checkForm(encode,timeOut);
if (checkForm