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
     * @return
     */
    public boolean tryLock(String lockKey) {
        return tryLock(lockKey, 5, 10);
    }

    /**
     * 加锁
     *
     * @param lockKey 锁的key
     * @return
     */
    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
     * @return
     */
    public RLock lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * 加锁
     *
     * @param lockKey 锁的key
     * @param timeout 超时时间
     * @return
     */
    public RLock lock(String lockKey, long timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, TimeUnit.SECONDS);
        return lock;
    }

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

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