1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| @Aspect @Component public class RepeatSubmitAspect {
private final static Logger LOGGER = LoggerFactory.getLogger(RepeatSubmitAspect.class);
@Autowired private RedisLock redisLock;
@Pointcut("@annotation(noRepeatSubmit)") public void pointCut(NoRepeatSubmit noRepeatSubmit) { }
@Around("pointCut(noRepeatSubmit)") public Object around(ProceedingJoinPoint pjp, NoRepeatSubmit noRepeatSubmit) throws Throwable { int lockSeconds = noRepeatSubmit.lockTime();
HttpServletRequest request = RequestUtils.getRequest(); Assert.notNull(request, "request can not null");
String token = request.getHeader("Authorization"); String path = request.getServletPath(); String key = getKey(token, path); String clientId = getClientId();
boolean isSuccess = redisLock.tryLock(key, clientId, lockSeconds);
if (isSuccess) { LOGGER.info("tryLock success, key = [{}], clientId = [{}]", key, clientId); Object result; try { result = pjp.proceed();
} finally { redisLock.releaseLock(key, clientId); LOGGER.info("releaseLock success, key = [{}], clientId = [{}]", key, clientId);
}
return result;
} else { LOGGER.info("tryLock fail, key = [{}]", key); return new ResultBean(ResultBean.FAIL, "重复请求,请稍后再试", null); }
}
private String getKey(String token, String path) { return token + path; }
private String getClientId() { return UUID.randomUUID().toString(); }
}
|