package org.jeecg.modules.utils;

import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * redis 锁
 */
public class RedisLockUtil {

    private RedisLockUtil() {
    }

    private static RedisTemplate<String, Object> redisTemplate;

    public static void setService(RedisTemplate<String, Object> redisTemplate) {
        RedisLockUtil.redisTemplate = redisTemplate;
    }

    /**
     * @param key 键
     * @return
     */
    public static boolean lock(String key) {
        /**
         * 默认期望过期时间
         */
        Long expireTime = 6000L;
        return lock(key, expireTime);
    }

    /**
     * @param key        键
     * @param expireTime 过期时间
     * @return
     */
    public static boolean lock(String key, Long expireTime) {
        if (key == null) {
            return false;
        }
        Boolean flag = redisTemplate.hasKey(key);
        if (Boolean.FALSE.equals(flag)) {
            redisTemplate.opsForValue().set(key, key, expireTime, TimeUnit.MILLISECONDS);
            return true;
        } else {
            return false;
        }
    }

    public static boolean unlock(String key) {
        if (key == null) {
            return true;
        } else {
            return Boolean.TRUE.equals(redisTemplate.delete(key));
        }
    }
}
