Redis分布式锁

本文最后更新于:10 个月前

方案一:推荐直接使用Redisson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Autowired
private Redisson redisson;

private void test() {
RLock lock = redisson.getLock("redis key");
try {
if (lock.tryLock(3L, TimeUnit.SECONDS)) {
try {
// do something...
} finally {
lock.unlock();
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
1
2
3
4
5
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.4</version>
</dependency>

方案二:

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
/**
* Redis 分布式锁
*
**/
@Component
public class RedisLockUtils {

@Autowired
private RedisTemplate redisTemplate;

//分布式锁过期时间 s 可以根据业务自己调节
private static final Long LOCK_REDIS_TIMEOUT = 10L;
//分布式锁休眠 至 再次尝试获取 的等待时间 ms 可以根据业务自己调节
public static final Long LOCK_REDIS_WAIT = 500L;


/**
* 加锁
**/
public Boolean getLock(String key,String value){
Boolean lockStatus = this.redisTemplate.opsForValue().setIfAbsent(key,value, Duration.ofSeconds(LOCK_REDIS_TIMEOUT));
return lockStatus;
}

/**
* 释放锁
**/
public Long releaseLock(String key,String value){
String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript,Long.class);
Long releaseStatus = (Long)this.redisTemplate.execute(redisScript, Collections.singletonList(key),value);
return releaseStatus;
}
}

Redis分布式锁
http://kevinw-m.github.io/2023/07/01/技术博客/java/Redis分布式锁/
作者
Kevin Wu
发布于
2023年7月1日
更新于
2023年10月28日
许可协议