package com.pcloud.book.skill.remind;

import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.exceptions.JedisException;

import java.util.UUID;

public class RedisTool {

    private final static Logger LOGGER = LoggerFactory.getLogger(RedisTool.class);
    /**
     * 加锁
     * @param lockName       锁的key
     * @param acquireTimeout 获取超时时间
     * @param timeout        锁的超时时间
     * @return 锁标识
     */
    public static String lockWithTimeout(String lockName, long acquireTimeout, long timeout) {
        String retIdentifier = null;
        try {
            // 随机生成一个value
            String identifier = UUID.randomUUID().toString();
            // 锁名，即key值
            String lockKey = "lock:" + lockName;
            // 超时时间，上锁后超过此时间则自动释放锁
            int lockExpire = (int) (timeout / 1000);
            // 获取锁的超时时间，超过这个时间则放弃获取锁
            long end = System.currentTimeMillis() + acquireTimeout;
            while (System.currentTimeMillis() < end) {
                if (JedisClusterUtils.setnx(lockKey, identifier)) {
                    JedisClusterUtils.expire(lockKey, lockExpire);
                    retIdentifier = identifier;
                    return retIdentifier;
                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        } catch (JedisException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return retIdentifier;
    }

    /**
     * 释放锁
     * @param lockName   锁的key
     * @param identifier 释放锁的标识
     * @return
     */
    public static boolean releaseLock(String lockName, String identifier) {
        String lockKey = "lock:" + lockName;
        boolean retFlag = false;
        try {
            if (identifier.equals(JedisClusterUtils.get(lockKey))) {
                JedisClusterUtils.del(lockKey);
                retFlag = true;
            }
        } catch (JedisException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return retFlag;
    }


    public static boolean lock(String key){
        //加锁，如果返回1为true，表示已经加锁，如果再来存储同一个key会返回0为false
        Boolean flag = JedisClusterUtils.setnx(key,"lock");
        //如果为true的话，设置一个过期时间，防止锁释放不掉
        if(flag){
            JedisClusterUtils.expire(key,50);
        }
        return flag;
    }

}
