55import org .aspectj .lang .ProceedingJoinPoint ;
66import org .aspectj .lang .annotation .Around ;
77import org .aspectj .lang .annotation .Aspect ;
8+ import org .aspectj .lang .reflect .MethodSignature ;
9+ import org .springframework .lock .annotation .OptimisticLock ;
10+
11+ import java .lang .reflect .Field ;
12+ import java .lang .reflect .Method ;
13+ import java .util .concurrent .atomic .AtomicBoolean ;
14+
15+ import static java .lang .Thread .sleep ;
816
917/**
1018 * 乐观锁的切面
@@ -25,8 +33,48 @@ public class OptimisticLockAspect {
2533 */
2634 @ Around ("@annotation(org.springframework.lock.annotation.OptimisticLock)" )
2735 public Object aroundOptimisticLock (ProceedingJoinPoint jp ) throws Throwable {
28- Object result = jp .proceed ();
36+ Object obj = jp .getTarget ();
37+ Class <?> clz = obj .getClass ();
38+ // 获取等待时长,默认500毫秒
39+ long waitTime = 500L ;
40+ MethodSignature signature = (MethodSignature ) jp .getSignature ();
41+ Method method = signature .getMethod ();
42+ if (method != null ) {
43+ OptimisticLock annotation = method .getAnnotation (OptimisticLock .class );
44+ if (annotation != null ) {
45+ waitTime = annotation .value ();
46+ }
47+ }
48+ // 获取锁对象
49+ AtomicBoolean lock = null ;
50+ for (Field field : clz .getDeclaredFields ()) {
51+ if ("$opLock" .equals (field .getName ())){
52+ field .setAccessible (true );
53+ Object unknownLock = field .get (obj );
54+ lock = (AtomicBoolean ) unknownLock ;
55+ }
56+ }
57+ Object result = null ;
58+ if (lock != null ){
59+ while (true ){
60+ if (lock .compareAndSet (true , false ))
61+ // 拿到了锁
62+ break ;
63+ else
64+ // 如果没拿到锁就忙等待
65+ sleep (waitTime );
66+ }
67+ try {
68+ LOGGER .info (clz .getSimpleName () + "获得乐观锁" );
69+ result = jp .proceed ();
70+ LOGGER .info (clz .getSimpleName () + "释放乐观锁" );
71+ }finally {
72+ lock .set (true );
73+ }
74+ }else {
75+ LOGGER .warn (clz .getSimpleName () + "生成乐观锁失败,未能加锁" );
76+ result = jp .proceed ();
77+ }
2978 return result ;
3079 }
31-
3280}
0 commit comments