防止表单重复提交,重复请求。程序幂等性预防
需要用到Redis
自定义注解:
作用于方法上,打了此注解的方法会通过Spring AOP进行幂等性检查:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CheckIdempotency {
String model() default "";
int timeOut() default 10;
String ex() default "程序正在执行,请勿重复请求";
boolean delLock() default true;
}
AOP切面类:
对CheckIdempotency 自定义注解进行AOP操作,通过Redis的setNX分布式锁的特性进行幂等性检查:
@Aspect
@Component
public class CheckIdempotencyAop {
@Autowired
RedisTemplate redisTemplate;
@Pointcut("@annotation(com.qzsoft.common.annotation.CheckIdempotency)")
private void method() {
}
@Around(value = "method()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
Signature signature = pjp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method targetMethod = methodSignature.getMethod();
CheckIdempotency checkIdempotency = targetMethod.getAnnotation(CheckIdempotency.class);
String model = checkIdempotency.model();
int timeOut = checkIdempotency.timeOut();
String ex = checkIdempotency.ex();
Object[] values = pjp.getArgs();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < values.length; i++) {
stringBuffer.append(values[i]);
}
boolean success = setNx(stringBuffer+model,"java",timeOut,TimeUnit.SECONDS);
if(!success){
throw BusinessException.buildBiz(ex);
}
pjp.proceed(values);
if(checkIdempotency.delLock())
redisTemplate.delete(stringBuffer+model);
return true;
}
@AfterThrowing(value = "method()", throwing="throwinfo")
public void afterThrowing(JoinPoint pjp, Throwable throwinfo) {
Signature signature = pjp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method targetMethod = methodSignature.getMethod();
CheckIdempotency checkIdempotency = targetMethod.getAnnotation(CheckIdempotency.class);
String model = checkIdempotency.model();
String ex = checkIdempotency.ex();
Object[] values = pjp.getArgs();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < values.length; i++) {
stringBuffer.append(values[i]);
}
if(!ex.equals(throwinfo.getMessage()))
redisTemplate.delete(stringBuffer+model);
}
private boolean setNx(String key, String value, long expires, TimeUnit timeUnit) {
boolean flag = false;
try {
flag = (boolean) redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(key.getBytes(), value.getBytes(), Expiration.from(expires, timeUnit), RedisStringCommands.SetOption.ifAbsent()));
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
}
自定义注解调用实例:
在需要幂等性检查的方法上标注自定义注解:
@CheckIdempotency(model = CREATESAMPMODEL,timeOut = 35,ex = EX,delLock = false)
public boolean createSamples(String projId){
........
}