package com.xinelu.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @Description Redis锁工具类
 * @Author 纪寒
 * @Date 2022-10-24 10:00:00
 * @Version 1.0
 */
@SuppressWarnings("unused")
@Slf4j
@Component
public class RedisDistributedLockUtils {

    /**
     * 默认的有效时长
     */
    private static final long DEFAULT_EXPIRE_UNUSED = 30000L;

    @Resource
    private RedisLockRegistry redisLockRegistry;

    /**
     * 加锁
     *
     * @param lockKey 键
     */
    @SuppressWarnings("AlibabaLockShouldWithTryFinally")
    public void lock(String lockKey) {
        Lock lock = obtainLock(lockKey);
        lock.lock();
    }

    /**
     * 尝试获取锁
     *
     * @param lockKey 键
     * @return 结果
     */
    public boolean tryLock(String lockKey) {
        Lock lock = obtainLock(lockKey);
        return lock.tryLock();
    }

    /**
     * 尝试获取锁，带有时间单位
     *
     * @param lockKey 键
     * @param seconds 时间，单位秒
     * @return 结果
     */
    public boolean tryLock(String lockKey, long seconds) {
        Lock lock = obtainLock(lockKey);
        try {
            return lock.tryLock(seconds, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return false;
        }
    }

    /**
     * 释放锁
     *
     * @param lockKey 键
     */
    public void unlock(String lockKey) {
        try {
            Lock lock = obtainLock(lockKey);
            lock.unlock();
            redisLockRegistry.expireUnusedOlderThan(DEFAULT_EXPIRE_UNUSED);
        } catch (Exception e) {
            log.warn("分布式锁 [{}] 释放异常", lockKey, e);
        }
    }

    /**
     * 释放锁
     *
     * @param lockKey 键
     * @return 结果
     */
    private Lock obtainLock(String lockKey) {
        return redisLockRegistry.obtain(lockKey);
    }
}
