ny
昨天 b6f169fe43a2b13f351aefc152374fc7f0bc8cb7
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 jnpf.flowable.util;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
 
import java.util.Collections;
import java.util.concurrent.TimeUnit;
 
/**
 * 类的描述
 *
 * @author JNPF@YinMai Info. Co., Ltd
 * @version 5.0.x
 * @since 2025/1/9 14:19
 */
@Component
public class RedisLock {
    private static final String LOCK_KEY_PREFIX = "workflow-lock:";
 
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
 
    private String getLockKey(String lockName) {
        return LOCK_KEY_PREFIX + lockName;
    }
 
    // false表示设置失败
    public boolean lock(String lockName, String lockValue, long expireTime, TimeUnit unit) {
        Boolean result = redisTemplate.opsForValue().setIfAbsent(getLockKey(lockName), lockValue, unit.toSeconds(expireTime), TimeUnit.SECONDS);
        return result != null && result;
    }
 
    public boolean unlock(String lockName, String lockValue) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(getLockKey(lockName)), Collections.singletonList(lockValue));
        return result != null && result > 0;
    }
}