2026-06-25 a26b31cc9f3ee9b21b1a754e80fa7359e8a7a8f8
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
package cn.iocoder.yudao.module.pay.dal.redis.wallet;
 
import jakarta.annotation.Resource;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;
 
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
 
import static cn.iocoder.yudao.module.pay.dal.redis.RedisKeyConstants.PAY_WALLET_LOCK;
 
/**
 * 支付钱包的锁 Redis DAO
 *
 * @author 芋道源码
 */
@Repository
public class PayWalletLockRedisDAO {
 
    @Resource
    private RedissonClient redissonClient;
 
    public <V> V lock(Long id, Long timeoutMillis, Callable<V> callable) throws Exception {
        String lockKey = formatKey(id);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
            // 执行逻辑
            return callable.call();
        } catch (Exception e) {
            throw e;
        } finally {
            lock.unlock();
        }
    }
 
    private static String formatKey(Long id) {
        return String.format(PAY_WALLET_LOCK, id);
    }
 
}