1.定义一个切面
@Aspect
@Component
public class NoRepeatSubmitAspect {
}
2.定义切点
@Aspect
@Component
public class NoRepeatSubmitAspect {
@Resource
private RedisTemplate<String,Object> redisTemplate;
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
//切点是所有注解的方法
@Pointcut("@annotation(com.bairh.cs.provider.controller.busi.NoRepeat)")
public void pointCut(){};
}
3.定义增强
@Aspect
@Component
public class NoRepeatSubmitAspect {
@Resource
private RedisTemplate<String,Object> redisTemplate;
@Autowired
private HttpServletRequest request;
@Autowired
private HttpServletResponse response;
@Pointcut("@annotation(com.bairh.cs.provider.controller.busi.NoRepeat)")
public void pointCut(){};
@Before("pointCut()")
public void before(JoinPoint joinPoint) throws IOException {
//获取corTicket
String corTicket = request.getHeader("Corticket");
MethodSignature signature =(MethodSignature)joinPoint.getSignature();
Method method = signature.getMethod();
//获取方法名
String methodName = method.getName();
//获取类名
Class<?> declaringClass = method.getDeclaringClass();
String className = declaringClass.getName();
//获取注解的timeOut值
NoRepeat annotation = method.getAnnotation(NoRepeat.class);
long timeOut = annotation.timeOut();
System.out.println(corTicket+"-"+className+"-"+methodName);
if (!redisTemplate.hasKey(corTicket + "-" + className + "-" + methodName)){
redisTemplate.opsForValue().set(corTicket+"-"+className+"-"+methodName,"true",timeOut, TimeUnit.SECONDS);
}
else {
throw new RuntimeException("不可重复提交");
}
}
}
4.定义注解
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeat {
long timeOut() default 5L;
}
5.使用注解
@NoRepeat
@PostMapping("/save")
public Object save(){
...
}