1. 程式人生 > 實用技巧 >springboot 重複提交

springboot 重複提交





@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DuplicateSubmitToken {

String key() default "";
}





@Aspect
@Configuration
public class LockMethodAop {

private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
// 最大快取 100 個
.maximumSize(1000)
// 設定寫快取後 5 秒鐘過期
.expireAfterWrite(1, TimeUnit.SECONDS)
.build();

@Autowired
HttpServletRequest request;

@Around("execution(* tz.lion.inv.manage.controller..*.*(..)) && @annotation(tz.lion.inv.manage.annotation.DuplicateSubmitToken)")
public Object interceptor(ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
DuplicateSubmitToken localLock = method.getAnnotation(DuplicateSubmitToken.class);
String key = localLock.key()+request.getSession().getId();
if (!StringUtils.isEmpty(key)) {
if (CACHES.getIfPresent(key) != null) {
throw new Exception(ErrorMsg.FORM_SUBMIT_REPEAT);
}
// 如果是第一次請求,就將 key 當前物件壓入快取中
CACHES.put(key, key);
}
try {
return pjp.proceed();
} catch (Throwable throwable) {
throw new RuntimeException("伺服器異常");
} finally {
// CACHES.invalidate(key);
}
}
}