package com.elab.redis.utils;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @Module 工具类
 * @Description redisLock相关的工具类
 * @Author liukaixiong
 * @Date 2021/1/5 13:21
 */
public class RedisLockUtils {
    private static Logger logger = LoggerFactory.getLogger(RedisLockUtils.class);


    public static <T> T lock(RedissonClient redissonClient, String key, Supplier<T> supplier) {
        return lock(redissonClient, key, false, 0L, supplier);
    }

    /**
     * 获取分布式锁
     *
     * @param redissonClient redisson对象
     * @param key            锁的key
     * @param supplier       具体执行的业务逻辑代码
     * @param isWait         没有抢到锁的情况是否会等待
     * @param timeOut        等待的超时时间
     * @param <T>            返回的结果
     * @return
     */
    public static <T> T lock(RedissonClient redissonClient, String key, boolean isWait, Long timeOut, Supplier<T> supplier) {
        RLock lock = redissonClient.getLock(key);
        try {
            if (isTryLock(lock, isWait, timeOut)) {
                return supplier.get();
            }
        } finally {
            releaseLock(lock);
        }
        return null;
    }

    private static boolean isTryLock(RLock lock, boolean isWait, Long timeOut) {
        if (isWait) {
            try {
                return lock.tryLock(timeOut, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                logger.warn("lock wait time out : " + e.getLocalizedMessage() + " time out : " + timeOut);
                return false;
            }
        } else {
            return lock.tryLock();
        }
    }


    /**
     * 锁释放
     *
     * @param lock
     */
    public static void releaseLock(RLock lock) {
        if (lock.isLocked() && lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }

}
