1、问题描述
- 用户点击过快导致前端发起多次请求。
- 恶意刷接口。
- 前端未知情况导致请求提交多次。
- 等等
以上情况都有可能导致出现异常数据
2、示例
NoRepeatSubmit.java
package com.hsshy.beam.common.annotion;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.PARAMETER, ElementType.METHOD}) // 作用到方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时有效
public @interface NoRepeatSubmit {
}
NoRepeatSubmitAspect.java
package com.hsshy.beam.seckill.aspectj;
import com.hsshy.beam.common.utils.R;
import com.hsshy.beam.common.utils.RedisUtil;
import com.hsshy.beam.common.utils.ToolUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Scope
@Aspect
@Order(1)
public class NoRepeatSubmitAspect {
@Autowired
private RedisUtil redisUtil;
//Service层切点 用于记录错误日志
@Pointcut("@annotation(com.hsshy.beam.common.annotion.NoRepeatSubmit)")
public void lockAspect() {
}
@Around("lockAspect()")
public Object around(ProceedingJoinPoint joinPoint) {
Object obj = null;
String key1 = joinPoint.getArgs()[0].toString();
String key2 = joinPoint.getArgs()[1].toString();
if(ToolUtil.isNotEmpty(redisUtil.get("repeat_"+key1+":"+key2))){
System.out.println("重复订单:"+key2);
return R.fail("订单重复提交");
}
else {
redisUtil.set("repeat_"+key1+":"+key2,"1",2L);
try {
obj = joinPoint.proceed();
} catch (Throwable e) {
e.printStackTrace();
throw new RuntimeException();
} finally{
}
return obj;
}
}
}
网友评论