RedisTemplate分布式锁实现

本文介绍了如何使用Java与Redis配合实现分布式锁,通过TRY_LOCK_SCRIPT和RELEASE_LOCK_SCRIPT脚本展示了tryLock和releaseLock方法的工作原理,适用于高并发场景下的锁管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private static final Long LOCK_SUCCESS = 1L;
private static final String TRY_LOCK_SCRIPT = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";
private static final String RELEASE_LOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

public Boolean tryLock(String lockKey, String identify, long expireTime) {
   try {
        RedisScript<String> redisScript = new DefaultRedisScript<>(TRY_LOCK_SCRIPT, String.class);
        Object result = redisStringTemplate.execute(redisScript, Collections.singletonList(lockKey), identify, expireTime);
        if (LOCK_SUCCESS.equals(result)) {
            return Boolean.TRUE;
        }
    } catch (Exception e) {
        log.error("获取锁失败,lockKey=[{}], identify=[{}]", lockKey, identify, e);
    }
    return Boolean.FALSE;
}

public Boolean releaseLock(String lockKey, String identify) {
    try {
        RedisScript<String> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_SCRIPT, String.class);
        Object result = redisStringTemplate.execute(redisScript, Collections.singletonList(lockKey), identify);
        if (LOCK_SUCCESS.equals(result)) {
            return Boolean.TRUE;
        }
    } catch (Exception e) {
        log.error("解锁失败,lockKey=[{}], identify=[{}]", lockKey, identify, e);
    }
    return Boolean.FALSE;
}
### 使用 RedisTemplate 实现分布式锁 #### 方法概述 为了使用 `RedisTemplate` 实现分布式锁,通常会采用基于 Redis 的 SETNX (SET if Not eXists) 原语来创建一个键作为锁。如果设置成功,则表示获取到了锁;否则说明已经有其他客户端持有该锁。 具体来说,在尝试获得锁时,程序应该执行如下逻辑: - 如果返回值为 1 表明当前线程获得了这把锁,并可继续后续业务处理流程; - 若返回值为 0 则意味着未能取得锁,此时应等待一段时间重试直至超时放弃竞争或对方释放资源为止[^4]。 此外,考虑到死锁预防等问题,还需要设定合理的过期时间以防止因异常情况而导致永久占用现象发生。当解锁时则简单删除对应的key即可完成整个过程[^2]。 下面给出一段具体的 Java 代码示例展示如何利用 Spring 提供的 `RedisTemplate` 来构建这样的机制: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; @Component public class DistributedLock { private final StringRedisTemplate stringRedisTemplate; @Autowired public DistributedLock(StringRedisTemplate stringRedisTemplate){ this.stringRedisTemplate = stringRedisTemplate; } /** * 获取分布式锁. * * @param lockKey 锁名称 * @param requestId 请求ID,用于区分不同请求方 * @param expireTimeMs 过期时间(ms), 防止死锁 */ public boolean tryGetDistributedLock(final String lockKey, final String requestId, long expireTimeMs) { Boolean result = stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(lockKey.getBytes(), requestId.getBytes(), java.util.concurrent.TimeUnit.MILLISECONDS.toSeconds(expireTimeMs), true)); return Boolean.TRUE.equals(result); } /*** * 解除分布式锁 * @param lockKey 锁名称 * @param requestId 请求ID */ public void releaseDistributedLock(String lockKey, String requestId) { // Lua 脚本确保原子性操作:只有当lockKey存在且value等于requestId时才删除此记录 String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1]" + "then" + "return redis.call('del', KEYS[1])" + "else" + "return 0" + "end"; Object unlockResult = stringRedisTemplate.execute( new DefaultRedisScript<>(luaScript, Long.class), Collections.singletonList(lockKey), requestId); if (!Objects.equals(unlockResult, 1L)) { throw new RuntimeException("Failed to release distributed lock"); } } } ``` 上述代码实现了两个主要的功能函数——`tryGetDistributedLock()` 和 `releaseDistributedLock()`.前者负责尝试加锁并指定了最大等待时间和唯一的请求 ID;后者则是用来安全地移除已经持有的锁实例[^1].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值