How Java annotations implement distributed locks based on redission

Time:2020-6-29

This article mainly introduces how to realize the distributed lock based on Redission with Java annotation. The sample code in this article is very detailed, which has a certain reference value for everyone to learn or work

1. Define annotation class

@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DistributedLock {
  //Lock name
  String lockName() default "";

  //Release time
  long releaseTime() default 5*1000;

  //Time unit
  TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
}

2. Define facet interception distributedlock annotation

@Aspect
@Component
@Slf4j
public class DistributedLockAspect {

  @Autowired
  private RedissonClient redissonClient;
   //The corresponding package name needs to be modified here
  @Pointcut("@annotation(com.utils.annotation.DistributedLock)")
  public void RlockAspect() {
  }

  @Around("RlockAspect()")
  public Object arround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    Object object = null;
    RLock lock = null;

    log.info("rlockAspect start ");

    try {
      DistributedLock rlockInfo = getRlockInfo(proceedingJoinPoint);
      String lockKey = getLocalKey(proceedingJoinPoint, rlockInfo);
      lock = redissonClient.getLock(lockKey);

      if (lock != null) {
        final boolean status = lock.tryLock(rlockInfo.releaseTime(), rlockInfo.timeUnit());
        if (status) {
          object = proceedingJoinPoint.proceed();
        }
      } else {
        log.info ("lock not acquired: {}", lockkey);
      }
    } finally {
      //The current thread obtains the lock and releases the lock
      if (lock != null && lock.isHeldByCurrentThread()) {
        lock.unlock();
      }
    }
    return object;
  }

  public DistributedLock getRlockInfo(ProceedingJoinPoint proceedingJoinPoint) {
    MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
    return methodSignature.getMethod().getAnnotation(DistributedLock.class);
  }

  /**
   *Get redis lock key
   *
   * @param proceedingJoinPoint
   * @return
   */
  public String getLocalKey(ProceedingJoinPoint proceedingJoinPoint, DistributedLock rlockInfo) {
    StringBuilder localKey = new StringBuilder("Rlock");
    final Object[] args = proceedingJoinPoint.getArgs();
    String businessNo = "";

    //If the lock value is not set
    if (StringUtils.isNotEmpty(rlockInfo.lockName())) {
      businessNo = rlockInfo.lockName();
    } else {
      MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
      Class[] parameters = methodSignature.getParameterTypes();
      String methodName = methodSignature.getMethod().getName();

      if (parameters != null) {
        for (int i = 0; i < parameters.length; i++) {
          Class parameter = parameters[i];
          if (parameter.getSimpleName().equals("NDevice")) {
            NDevice de = (NDevice) args[i];
            businessNo = de.getUuid() + methodName;
          }
          if (parameter.getSimpleName().equals("FrameBean")) {
            FrameBean de = (FrameBean) args[i];
            businessNo = de.getColumn1() + methodName;
          }
        }
        //If the business number is not obtained, the method signature is used
        if (StringUtils.isEmpty(businessNo)) {
          businessNo = methodName;
        }
      }
    }
    return businessNo;
  }
}

3. Usage: add @ distributedlock annotation to the method requiring distributed lock

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.