package com.yxcheng.token.common.cache.distributelock;

import com.yxcheng.token.common.cache.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ScheduledControll {

    @Autowired
    private RedisService redisService;


    public boolean getScheduledLock(String key,int expire) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisService.getRedisTemplate().getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();

        if ((null == increment || increment.longValue() == 0) && expire > 0) {//初始设置过期时间
            entityIdCounter.expire(expire, TimeUnit.SECONDS);
        }
        //redis值大于0，获取锁失败。
        if(increment>0){
            return false;
        }else{
            return true;
        }
    }

    public void delScheduledLock(String key) {
        redisService.del(key);
    }
}
