1
zj
2025-10-12 84d42b6997ae87fa64b75ae085fce11d05a6ca5a
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.ruoyi.im.util;
 
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
import java.util.concurrent.TimeUnit;
 
@Component
public class RedisDistributedLock {
 
    private final RedisTemplate<Object, Object> redisTemplate;
 
    private static final String LOCK_PREFIX = "insurance:lock:";
 
    public RedisDistributedLock(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
 
    /**
     * 尝试获取锁
     * @param lockKey 锁的key
     * @param expireSeconds 锁过期时间(秒)
     * @param waitSeconds 等待时间(秒)
     * @return 是否获取成功
     */
    public boolean tryLock(String lockKey, long expireSeconds, long waitSeconds) {
        String key = LOCK_PREFIX + lockKey;
        long endTime = System.currentTimeMillis() + waitSeconds * 1000;
 
        while (System.currentTimeMillis() < endTime) {
            Boolean success = redisTemplate.opsForValue().setIfAbsent(key, "locked", expireSeconds, TimeUnit.SECONDS);
            if (Boolean.TRUE.equals(success)) {
                return true;
            }
 
            try {
                // 短暂休眠后重试
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
        return false;
    }
 
    /**
     * 获取锁(使用默认参数)
     */
    public boolean tryLock(String lockKey) {
        return tryLock(lockKey, 30L, 10L);
    }
 
    /**
     * 释放锁
     * @param lockKey 锁的key
     */
    public void releaseLock(String lockKey) {
        String key = LOCK_PREFIX + lockKey;
        redisTemplate.delete(key);
    }
 
 
    /**
     * 生成锁的key(基于用户ID和产品ID)
     */
    public String generateLockKey(String account, Integer productId) {
        // 将 %d 改为 %s 来格式化字符串
        return String.format("purchase:%s:%d", account, productId);
    }
 
    /**
     * 生成基于用户ID的锁key
     */
    public String generateUserLockKey(String account) {
        // 同样修正这里
        return String.format("purchase:%s", account);
    }
}