package com.winsun.utils;


import com.mysql.cj.util.TimeUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;


import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class RedisLockUtil {

    @Resource
    private RedisTemplate<String, String>  redisTemplate;

    /**
    * 创建锁
    *
    * @param key         锁的Key
    * @param value       值(随便写毫无意义)
    * @param releaseTime 锁过期时间 防止死锁
    * @return
    */
    public  Boolean redisLock(String key,String value,long releaseTime){
        try{
            boolean boo = false;
            synchronized(this){
                boo = redisTemplate.opsForValue().setIfAbsent(key,value);
            }

            if(boo){
                redisTemplate.expire(key, releaseTime, TimeUnit.SECONDS);
                return true;
            }
        }catch (Exception e){
            redisTemplate.delete(key);
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 根据key'删除锁
     *
     * @param key
     */
    public synchronized void deleteLock(String key){
        // 删除key即可释放锁
        redisTemplate.delete(key);
    }

}
