package com.app.util.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Demo示例代码：
 * long currentTimeMills = System.currentTimeMillis();
 * String redisLockValue = String.valueOf(currentTimeMills + RedisConstants.LOCK_EXPIRE_TIME);
 * final boolean lock = redisLock.lock(String.valueOf(seckillId), redisLockValue);
 * if (!lock) {
 * throw new RuntimeException("人数过多，请稍后再试");
 * }
 * try {
 * SeckillExecution execution = secPressureTestService.executeSeckill(seckillId);
 * return Result.success(execution);
 * } catch (Exception e) {
 * log.error("【执行秒杀错误】,message={}", e.getMessage());
 * return Result.error(e.getMessage());
 * } finally {
 * redisLock.unlock(String.valueOf(seckillId), redisLockValue);
 * }
 */
@Slf4j
@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 功能描述：加锁
     *
     * @param key   seckillId
     * @param value 当前时间+超时时间
     * @return
     */
    public Boolean lock(String key, String value) {
        /* 可以设置返回true */
        Boolean isLock = redisTemplate.opsForValue().setIfAbsent(key, value);
        if (isLock) {
            return Boolean.TRUE;
        }

        String currentValue = redisTemplate.opsForValue().get(key);
        /* 如果锁已经过期 */
        if (!StringUtils.isEmpty(currentValue) && Long.valueOf(currentValue) < System.currentTimeMillis()) {
            /* 获取上一个锁的时间，并设置新锁的时间 */
            String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
            if (!StringUtils.isEmpty(oldValue) && oldValue.equals(currentValue)) {
                log.info("锁过期并返回true");
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }

    /**
     * 功能描述：解锁
     *
     * @param key
     * @return
     */
    public void unlock(String key, String value) {
        try {
            String currentValue = redisTemplate.opsForValue().get(key);
            if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
                redisTemplate.opsForValue().getOperations().delete(key);
            }
        } catch (Exception e) {
            log.error("redis分布式锁，解锁异常, {}", e.getMessage());
        }
    }

}
