sprongboot redis分布式锁
时间: 2025-01-07 09:54:12 浏览: 22
Spring Boot 实现 Redis 分布式锁
在分布式环境中,为了防止多个实例同时处理相同的数据而导致数据不一致的情况发生,在 Spring Boot 应用程序中可以利用 Redis 来创建分布式锁。下面介绍一种基于 Redis 的简单而有效的分布式锁实现方式。
使用 Lettuce 客户端操作 Redis 锁
Lettuce 是一个线程安全的客户端库,支持异步执行命令以及自动重连机制等功能特性,非常适合用来构建高可用的应用场景下的分布式锁服务[^1]。
import io.lettuce.core.RedisClient;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
public class DistributedLock {
private final String lockKey; // 锁键名
private final long expireTimeMs; // 过期时间毫秒数
public DistributedLock(String key, int timeoutSecs){
this.lockKey = "lock:" + key;
this.expireTimeMs = (long)(timeoutSecs * 1000);
}
/**
* 尝试获取锁
*/
public boolean tryAcquire(){
StatefulRedisConnection<String, String> connection = null;
try{
RedisClient client = RedisClient.create("redis://localhost");
connection = client.connect();
RedisCommands<String, String> syncCmds = connection.sync();
Long result = syncCmds.set(lockKey,"locked",
SetArgs.Builder.nx().px(expireTimeMs));
return Objects.nonNull(result) && Boolean.TRUE.equals(result==1);
} finally {
if(connection != null){
connection.close();
}
}
}
/**
* 释放锁
*/
public void release() throws Exception{
StatefulRedisConnection<String, String> connection = null;
try{
RedisClient client = RedisClient.create("redis://localhost");
connection = client.connect();
RedisCommands<String, String> syncCmds = connection.sync();
// 只有当 value 值相等时才删除该 key-value 对应关系
syncCmds.eval(
"if redis.call('get', KEYS[1]) == ARGV[1]" +
"then return redis.call('del', KEYS[1])" +
"else return 0 end",
Arrays.asList(lockKey),
Collections.singletonList("locked"));
}finally{
if(connection!=null){
connection.close();
}
}
}
}
此代码片段展示了如何通过 SET
命令设置带有过期时间和条件(仅当不存在指定key时才会成功)参数来尝试获得锁;并通过 Lua 脚本原子化地检查并移除已存在的锁记录以确保安全性[^2]。
相关推荐

















