package com.zksy.pole.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class LockUtils {
    @Autowired
    private RedissonClient redissonClient;
    /**
     * 尝试获取锁。
     *
     * @param key 锁的键
     * @return 是否成功获取锁
     */
    public boolean lock(String key) {
        RLock lock = redissonClient.getLock(key);
        return lock.tryLock();
    }

    public RLock getLock(String key) {
        return redissonClient.getLock(key);
    }

    /**
     * 释放锁。
     *
     * @param key 锁的键
     * @return 是否成功释放锁
     */
    public boolean unlock(String key) {
        RLock lock = redissonClient.getLock(key);
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
            return true;
        }
        return false;
    }
    public boolean forceUnlock(String key) {
        RLock lock = redissonClient.getLock(key);
        if (lock.isHeldByCurrentThread()) {
            lock.forceUnlock();
            return true;
        }
        return false;
    }

    /**
     * 检查锁是否被占用。
     *
     * @param key 锁的键
     * @return 锁是否被占用
     */
    public boolean isLocked(String key) {
        RLock lock = redissonClient.getLock(key);
        return lock.isLocked();
    }
}
