pom文件加入aop依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
自定义注解
@Target(ElementType.METHOD) // 作用到方法上
@Retention(RetentionPolicy.RUNTIME) // 运行时有效
public @interface NoRepeatSubmit {
//名称,如果不给就是要默认的
String name() default "name";
}
使用aop
@Aspect
@Component
@Slf4j
public class NoRepeatSubmitAop {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 切入点
*/
@Pointcut("@annotation(cn.yunwan.common.NoRepeatSubmit)")
public void cut() {
}
@Around("cut()")
public Object arround(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
assert attributes != null;
HttpServletRequest request = attributes.getRequest();
String token = request.getHeader("Token");
//这里是唯一标识 根据情况而定(我这里根据token)
String key = token + "-" + request.getServletPath();
// 如果缓存中有这个url视为重复提交
if (!redisTemplate.hasKey(key)) {
//通过,执行下一步
Object o = joinPoint.proceed();
//然后存入redis 并且设置5s倒计时
redisTemplate.opsForValue().set(key, "0",5, TimeUnit.SECONDS);
return o;
} else {
return CommonResult.failed( "请勿重复提交或者操作过于频繁!");
}
}
}
注解作用到方法接口上
@NoRepeatSubmit(name = "test") //
@GetMapping("test")
public Result test() {
return Result.success("测试!");
}