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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| ** * redis锁 * */ @Aspect @Component public class RedisLockAspect {
private final Logger log = LoggerFactory.getLogger(RedisLockAspect.class);
@Autowired private RedisService redisService;
@Pointcut("@annotation(cn.avicnet.uap.common.redis.annotation.RedisLock)") public void pointCut() { }
@Around("pointCut()") public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
RedisLock annotation = getAnnotation(joinPoint); if (annotation == null || StringUtils.isBlank(annotation.lockName())) { throw new CustomException("请设置锁名!:" + joinPoint.getSignature()); }
String lockName = annotation.lockName();
if (annotation.lockUser()) { Long userId = AsyncSecurityUtils.getUserId() != null ? AsyncSecurityUtils.getUserId() : this.getUserId(); lockName = lockName + ":" + userId; }
long lockTime; if (annotation.lockTime() <= 0L) { lockTime = 30 * 60 * 1000L; } else { lockTime = annotation.lockTime(); }
String timeTags = String.valueOf(System.currentTimeMillis() + lockTime);
if (!redisService.lock(lockName, timeTags)) { throw new CustomException("已有用户正在操作!"); }
Object obj; try { obj = joinPoint.proceed(); } catch (Exception e) { log.error(e.getMessage()); throw e; } finally { try { redisService.unlock(lockName, timeTags); } catch (Exception e) { log.error("redis 解锁失败" + e.getMessage()); } } return obj; }
private RedisLock getAnnotation(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod();
if (method != null) { return method.getAnnotation(RedisLock.class); } return null; }
public Long getUserId() { return ServletUtils.getRequest() == null ? null : Convert.toLong(ServletUtils.getRequest().getHeader(CacheConstants.DETAILS_USER_ID)); }
}
|