Pu Zhibing
2025-02-19 8f45afced0c6a4085560c62dbd58e6ef0f4cecf4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package com.ruoyi.web.tool;
 
import org.springframework.data.redis.core.RedisTemplate;
 
import java.util.UUID;
import java.util.concurrent.TimeUnit;
 
/**
 * @author zhibing.pu
 * @Date 2024/9/26 18:43
 */
public class RedisLock {
    private RedisTemplate redisTemplate;
    private String lockKey;
    private int expireTime; // 锁的超时时间
    private int timeout; // 获取锁的超时时间
    
    
    public RedisLock(RedisTemplate redisTemplate, String lockKey, int expireTime, int timeout) {
        this.redisTemplate = redisTemplate;
        this.lockKey = lockKey;
        this.expireTime = expireTime;
        this.timeout = timeout;
    }
    
    public boolean lock() {
        String identifier = UUID.randomUUID().toString();
        long end = System.currentTimeMillis() + timeout;
        while (System.currentTimeMillis() < end) {
            if (redisTemplate.opsForValue().setIfAbsent(lockKey, identifier, expireTime, TimeUnit.SECONDS)) {
                return true;
            }
            // 可以使用延时来减少CPU占用
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return false;
    }
    
    public void unlock() {
        redisTemplate.delete(lockKey);
    }
}