应用场景:前端页面出现卡顿,用户反复点击操作按钮,导致后台接口短时间内多次提交
- 创建一个接口类
public @interface NoRepeatSubmit {
String name() default "name:";
}
- 通过切面,设置调用该接口的类不可重复提交
/**
* 接口重复提交拦截切面(两秒内同一客户端不允许重复提交)
*/
@Aspect
@Configuration
public class SubmitAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
// 最大缓存 100 个
.maximumSize(100)
// 设置缓存过期时间为S
.expireAfterWrite(2, TimeUnit.SECONDS)
.build();
@Around("execution(public * *(..)) && @annotation(com.bos.common.NoRepeatSubmit)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Commit form = method.getAnnotation(Commit.class);
String key = getCacheKey(method, pjp.getArgs());
if (com.bos.util.StringUtils.isNotNullOrBlank(key)) {
if (CACHES.getIfPresent(key) != null) {
ResultData resultData = new ResultData();
resultData.setMessage("请勿重复提交");
resultData.setResult("false");
return resultData;
}
// 如果是第一次请求,就将key存入缓存中
CACHES.put(key, key);
}
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException("服务器异常");
} finally {
CACHES.invalidate(key);
}
}
private String getCacheKey(Method method, Object[] args) {
return method.getName() + args[0];
}
- 测试
/**
* 定时发送消息模板
*/
@GetMapping(value = "/sendCondition")
@NoRepeatSubmit
public void sendCondition() {
System.out.println("test");
}