Pu Zhibing
2025-03-31 97d99b76bdde8952cf257c3c85c1a8a080927af4
ruoyi-common/ruoyi-common-redis/src/main/java/com/ruoyi/common/redis/service/RedisService.java
@@ -6,6 +6,8 @@
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
@@ -273,4 +275,40 @@
    {
        return redisTemplate.keys(pattern);
    }
    /**
     * 加锁
     * @param key
     * @return
     */
    public boolean lock(String key){
        Boolean hasKey = redisTemplate.hasKey(key);
        if(!hasKey){
            redisTemplate.opsForValue().set(key, UuidUtil.getTimeBasedUuid().toString());
            return true;
        }
        //30秒的等待
        for (int i = 0; i < 60; i++) {
            hasKey = redisTemplate.hasKey(key);
            if(!hasKey){
                redisTemplate.opsForValue().set(key, UuidUtil.getTimeBasedUuid().toString());
                return true;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }
    /**
     * 解锁
     * @param key
     */
    public void unlock(String key){
        redisTemplate.delete(key);
    }
}