/**
 *  redission分布式锁,用来控制Scheduled定时任务
 *
 */
@Sl4j
@Aspect
@Component
public class LockAspect {
    private RedissonClient redissonClient;

    @Value("${spring.redis.cluster.nodes}")
    private List<String> redisClusterNodes;

    @Value("${spring.redis.password}")
    private String redisPassword;
    
    @PostConstruct
    private void init() {
        List<String> nodeAddressList = redisClusterNodes.stream().map(node -> "redis://" + node).collect(Collectors.toList());
        Config config = new Config();
        config.useClusterServers().setNodeAddresses(nodeAddressList);
        config.useClusterServers().setPassword(redisPassword);
        redissonClient = Redisson.create(config);
    }

    @Pointcut(value = "@annotation(DistributedLock)")
    public void pointcut() {}
    
    @Around("pointcut()&&@annotation(distributedLock)")
    public Object doAround(ProceedingJoinPoint joinPoint, DistributedLock distributedLock) throws Throwable {
        Object result = null;
        RLock lock = redissonClient.getLock("ecoPcenter:" + distributedLock.key());
        if (distributedLock.exclusive()) {
              if (!lock.tryLock()) {
                  log.info("key:{}为独占模式且已加锁,放弃本次执行", distributedLock.key());
                  return result;
              }
        } else {
                lock.lock();
        }
        log.info("加分布式锁{}", distributedLock.key());
        try {
            result = joinPoint.proceed(); 
        } finally {
            lock.unlock();
            log.info("解分布式锁{}", distributedLock.key());
        }
        return result;
    }
}


/**
 * 分布式锁注解
 * 
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DistributedLock {
    String key() default "defaultKey";
    boolean exclusive() default false;
}

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

/**
 * 修改支撑天数
 * 
 */
@DistributedLock(key = "updatedSupportTime", exclusive = true)
@Scheduled(cron = "0 1 13,0 * * *")
public void updateSupportTime() {}

 结合博文《记一次Redisson线上问题,你怎么能释放别人的锁》写法,判断是否合理释放加锁解锁在多线程情况下的处理:

https://mp.weixin.qq.com/s/uB6otYTrkZ3FcXltt5SeRQ

posted on 2024-06-19 00:26  人无名,则可专心练剑  阅读(79)  评论(0)    收藏  举报