欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java注解如何基于Redission实现分布式锁

时间:2021-11-13 15:29:52|栏目:JAVA代码|点击:

这篇文章主要介绍了Java注解如何基于Redission实现分布式锁,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1、定义注解类

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

  //释放时间
  long releaseTime() default 5*1000;

  //时间单位
  TimeUnit timeUnit() default TimeUnit.MILLISECONDS;
}

2、定义切面拦截 DistributedLock 注解

@Aspect
@Component
@Slf4j
public class DistributedLockAspect {

  @Autowired
  private RedissonClient redissonClient;
   //这里需要修改对应的包名
  @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("未获取到锁:{}", lockKey);
      }
    } finally {
      // 当前线程获取到锁再释放锁
      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);
  }

  /**
   * 获取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 (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 (StringUtils.isEmpty(businessNo)) {
          businessNo = methodName;
        }
      }
    }
    return businessNo;
  }
}

3、使用方法:在需要用分布式锁的方法上面加 @DistributedLock 注解即可

上一篇:java8如何用Stream查List对象某属性是否有重复

栏    目:JAVA代码

下一篇:Fluent Mybatis实现环境隔离和租户隔离

本文标题:Java注解如何基于Redission实现分布式锁

本文地址:http://www.codeinn.net/misctech/183366.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有