package com.supServer.common.utils;

import com.supServer.common.exception.ServiceException;
import com.supServer.common.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description：
 * @Author: ly
 * @Date: 2022/4/23 16:42
 */
@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate srt;
    //锁的超时时间
    private Integer lockTimeOut = 20;
    //获取锁超时时间
    private Integer timeOut = 20;

    /**
     * 加锁
     */
    public boolean lock(String key) {
        //生成存入redis锁的value值
        String uuid = UUID.randomUUID().toString();
        boolean b = false;
        Long time = System.currentTimeMillis();
        while(!(b = srt.opsForValue().setIfAbsent(key, uuid, lockTimeOut, TimeUnit.SECONDS))) {
            //判定获取锁是否超时
            if(System.currentTimeMillis() - time >= timeOut * 1000) {
                throw new ServiceException("加锁超时");
            }
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return b;
    }


    /**
     * 解锁
     */
    public void unLock(String key) {
        if(StringUtils.isNotBlank(key)) {
            srt.delete(key);
        }
    }
}

