package cn.iocoder.yudao.module.infra.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class DistributedLock {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public boolean lock(String key, long timeout, TimeUnit unit) {
        Boolean result = stringRedisTemplate.opsForValue().setIfAbsent(key, "locked", timeout, unit);
        return result != null && result;
    }

    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
