package com.winsun.utils;


import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


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

@Component
public class RedisLockUtil {

    @Resource
    private RedisTemplate<String, String>  redisTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    /**
    * 创建锁
    *
    * @param key         锁的Key
    * @param value       值(随便写毫无意义)
    * @param releaseTime 锁过期时间 防止死锁
    * @return
    */
    public synchronized Boolean redisLock(String key,String value,long releaseTime){
        try{
            boolean boo = redisTemplate.opsForValue().setIfAbsent(key,value,releaseTime, TimeUnit.MINUTES);
            if(boo){
                return true;
            }
            return false;
        }catch (Exception e){
            e.getMessage();
        }finally {
            deleteLock(key);
            return false;
        }
    }
    /**
     * 根据key'删除锁
     *
     * @param key
     */
    public synchronized void deleteLock(String key){
        // 删除key即可释放锁
        redisTemplate.delete(key);
    }

}
