记录防止多次提交方法:
1.创建注解类
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Resubmit {
/**
* 延时时间 在延时多久后可以再次提交
*
* @return Time unit is one second
*/
int delaySeconds() default 20;
/**
* 描述信息
* @return
*/
String message() default "操作频繁请稍后重试";
}
2.aop
@Slf4j
@Aspect
@Component
public class ResubmitAspect {
private final static Object PRESENT = new Object();
@Around("@annotation(com.baitao.ebay.common.annotation.Resubmit)")
public Object handleResubmit(ProceedingJoinPoint joinPoint) throws Throwable {
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
//获取注解信息
Resubmit annotation = method.getAnnotation(Resubmit.class);
int delaySeconds = annotation.delaySeconds();
String message = annotation.message();
Object[] pointArgs = joinPoint.getArgs();
String key = "";
//获取第一个参数
Object firstParam = pointArgs[0];
//解析参数
JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(firstParam));
if (firstParam != null) {
StringBuffer sb = new StringBuffer();
data.forEach((k, v) -> {
sb.append(v);
});
//生成加密参数 使用了content_MD5的加密方式
key = ResubmitLock.handleKey(sb.toString());
}
//执行锁
boolean lock = false;
try {
//设置解锁key
lock = ResubmitLock.getInstance().lock(key, PRESENT);
if (lock) {
//放行
return joinPoint.proceed();
} else {
//响应重复提交异常
return AjaxResult.error(message);
}
} finally {
//设置解锁key和解锁时间
ResubmitLock.getInstance().unLock(lock, key, delaySeconds);
}
}
}
3.锁
@Slf4j
public class ResubmitLock {
private static final ConcurrentHashMap<String, Object> LOCK_CACHE = new ConcurrentHashMap<>(200);
private static final ScheduledThreadPoolExecutor EXECUTOR = new ScheduledThreadPoolExecutor(5, new ThreadPoolExecutor.DiscardPolicy());
// private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
// 最大缓存 100 个
// .maximumSize(1000)
// 设置写缓存后 5 秒钟过期
// .expireAfterWrite(5, TimeUnit.SECONDS)
// .build();
private ResubmitLock() {
}
/**
* 静态内部类 单例模式
*
* @return
*/
private static class SingletonInstance {
private static final ResubmitLock INSTANCE = new ResubmitLock();
}
public static ResubmitLock getInstance() {
return SingletonInstance.INSTANCE;
}
public static String handleKey(String param) {
return DigestUtils.md5Hex(param == null ? "" : param);
}
/**
* 加锁 putIfAbsent 是原子操作保证线程安全
*
* @param key 对应的key
* @param value
* @return
*/
public boolean lock(final String key, Object value) {
return Objects.isNull(LOCK_CACHE.putIfAbsent(key, value));
}
/**
* 延时释放锁 用以控制短时间内的重复提交
*
* @param lock 是否需要解锁
* @param key 对应的key
* @param delaySeconds 延时时间
*/
public void unLock(final boolean lock, final String key, final int delaySeconds) {
if (lock) {
EXECUTOR.schedule(() -> {
LOCK_CACHE.remove(key);
}, delaySeconds, TimeUnit.SECONDS);
}
}
}
4.使用
@Resubmit(delaySeconds = 5, message = “操作频繁”)