|
|
@@ -0,0 +1,62 @@
|
|
|
+package com.nb.common.lock.aop;
|
|
|
+
|
|
|
+import com.nb.common.lock.SpElUtil;
|
|
|
+import com.nb.common.lock.annotation.DistributeLock;
|
|
|
+import org.aspectj.lang.ProceedingJoinPoint;
|
|
|
+import org.aspectj.lang.annotation.Around;
|
|
|
+import org.aspectj.lang.annotation.Aspect;
|
|
|
+import org.aspectj.lang.reflect.MethodSignature;
|
|
|
+import org.redisson.api.RLock;
|
|
|
+import org.redisson.api.RedissonClient;
|
|
|
+import org.springframework.context.annotation.Configuration;
|
|
|
+import org.springframework.core.annotation.AnnotationUtils;
|
|
|
+import org.springframework.dao.CannotAcquireLockException;
|
|
|
+
|
|
|
+/**
|
|
|
+ * @ClassName : DistributeLockAspect
|
|
|
+ * @Description :
|
|
|
+ * @Author : LF
|
|
|
+ * @Date: 2023年06月05日
|
|
|
+ */
|
|
|
+@Aspect
|
|
|
+@Configuration
|
|
|
+public class DistributeLockAspect {
|
|
|
+ private final RedissonClient redissonClient;
|
|
|
+
|
|
|
+ public DistributeLockAspect(RedissonClient redissonClient) {
|
|
|
+ this.redissonClient = redissonClient;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 进行加锁处理
|
|
|
+ * @param joinPoint
|
|
|
+ * @param distributeLock
|
|
|
+ * @return
|
|
|
+ * @throws Throwable
|
|
|
+ */
|
|
|
+ @Around("@annotation(distributeLock)")
|
|
|
+ public Object around(ProceedingJoinPoint joinPoint,
|
|
|
+ DistributeLock distributeLock) throws Throwable {
|
|
|
+ MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
|
|
+ distributeLock = AnnotationUtils.findAnnotation(methodSignature.getMethod(),DistributeLock.class);
|
|
|
+ String key = "lock:"+ SpElUtil.parseExpression(distributeLock.name(), methodSignature.getMethod(), joinPoint.getArgs());
|
|
|
+ //获取锁
|
|
|
+ RLock rLock = redissonClient.getFairLock(key);
|
|
|
+ int retryTime = distributeLock.retryTime();
|
|
|
+ //当重试次数小于等于0时,设置为1,即获取锁的次数最少为1次
|
|
|
+ retryTime=retryTime<=0?1:retryTime;
|
|
|
+ while (retryTime>0){
|
|
|
+ if(rLock.tryLock(distributeLock.waitTime(),distributeLock.leaseTime(),distributeLock.unit())){
|
|
|
+ try {
|
|
|
+ return joinPoint.proceed();
|
|
|
+ }finally {
|
|
|
+ if(rLock.isHeldByCurrentThread()){
|
|
|
+ rLock.unlock();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ --retryTime;
|
|
|
+ }
|
|
|
+ throw new CannotAcquireLockException("服务器繁忙,请稍后重试");
|
|
|
+ }
|
|
|
+}
|