@Aspect
@Component
public class NotRepeatedSubmitAspect {
private static final String LOCK_REPEATED_SUBMIT = "lock_repeated_submit:";
@Autowired
private RedissonClient redissonClient;
@Around("@annotation(notRepeatedSubmit)")
public Object around(ProceedingJoinPoint pjp, NotRepeatedSubmit notRepeatedSubmit) throws Throwable {
try {
//获取当前执行类
String className = pjp.getSignature().getDeclaringTypeName();
//获取当前执行类中的执行方法
String methodName = pjp.getSignature().getName();
// 参数
Map<String, Object> params = getRequestParams(pjp);
String md5 = SecureUtil.md5(className + methodName + JSON.toJSONString(params));
RLock lock = redissonClient.getLock(LOCK_REPEATED_SUBMIT+md5);
boolean tryLock = lock.tryLock();
if(tryLock){
try {
Object result = pjp.proceed();
return result;
} finally {
if (lock.isLocked() && lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
throw new BusinessException(notRepeatedSubmit.msg());
} catch (Throwable e) {
throw e;
}
}
/**
* 获取入参
* @param proceedingJoinPoint
*
* @return
* */
private Map<String, Object> getRequestParams(ProceedingJoinPoint proceedingJoinPoint) {
Map<String, Object> requestParams = new HashMap<>();
//参数名
String[] paramNames =
((MethodSignature)proceedingJoinPoint.getSignature()).getParameterNames();
//参数值
Object[] paramValues = proceedingJoinPoint.getArgs();
for (int i = 0; i < paramNames.length; i++) {
Object value = paramValues[i];
//如果是文件对象
if (value instanceof MultipartFile) {
MultipartFile file = (MultipartFile) value;
//获取文件名
value = file.getOriginalFilename();
}
if(value instanceof HttpServletResponse){
continue;
}
if(value instanceof HttpServletRequest){
continue;
}
requestParams.put(paramNames[i], value);
}
// 附加用户信息
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String principal = "";
if(null != authentication){
principal = authentication.getName();
}
requestParams.put("username",principal);
return requestParams;
}
}
分布式锁防重复提交
最新推荐文章于 2024-05-01 19:17:00 发布