package com.sckw.redis.config;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @Author xucaiqin
 * @date 2023-04-07 17:20:34
 */
@Component
@Slf4j
public class RedisLockUtil {
    @Resource
    private RedissonClient redissonClient;

    /**
     * 获取锁
     *
     * @param lockKey 锁的key
     */
    public RLock getLock(String lockKey) {
        return redissonClient.getLock(lockKey);
    }

    /**
     * 加锁
     * 默认加锁时间30秒
     *
     * @param lockKey 锁的key
     * @return
     */
    public boolean tryLock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        return lock.tryLock();
    }

    /**
     * 加锁
     * 默认加锁时间30秒
     *
     * @param lockKey  持有的锁key
     * @param waitTime 加锁等待时间
     * @return
     */
    public boolean tryLock(String lockKey, int waitTime) {
        return tryLock(lockKey, waitTime, -1);
    }

    /**
     * 加锁
     *
     * @param lockKey   锁的key
     * @param waitTime  加锁等待时间
     * @param leaseTime 锁自动释放时间
     */
    public boolean tryLock(String lockKey, int waitTime, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.info("tryLock lockKey:{} waitTime:{} leaseTime:{}", lockKey, waitTime, leaseTime);
            return false;
        }
    }


    /**
     * 解锁
     *
     * @param lockKey 锁的key
     */
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        if (lock.isHeldByCurrentThread() && lock.isLocked()) {
            lock.unlock();
        }
    }

    /**
     * 解锁
     *
     * @param lock 锁对象
     */
    public void unlock(RLock lock) {
        lock.unlock();
    }
}
