Redis加锁操作注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* redis锁
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RedisLock {

/**redis 锁名 */
String lockName() default "";

/**redis 锁持续时间 默认30min */
long lockTime() default 30 * 60 * 1000L;

/**redis 是否需要锁用户 */
boolean lockUser() default false;
}

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;
}

/**
* 从方法切入点获取注解
*
* @param joinPoint 切入点
* @return 注解信息
*/
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));
}

}