1. 基本介绍
分布式锁就是满足分布式系统或者集群模式下多线程课件并且互斥的锁。特性如下:
-
多线程可见
-
互斥
-
高可用
-
高性能
-
安全性
一般分布式锁的核心实现就是多线程之间互斥,mysql、zookeeper、redis 都可以实现分布式锁。
-
mysql 利用本身互斥锁机制(通过创建一张锁表,在需要加锁时向表中插入一条记录,释放锁时删除记录。),高可用(实现简单,稳定可靠。),但性能一般(无法适应高并发场景;容易出现死锁;无法优雅地实现阻塞式锁。),安全方面断开连接,就会自动释放锁
-
zookeeper 利用临时节点(节点唯一性和有序性实现互斥;基于 Zookeeper 的节点特性以及 watch 机制实现,通常使用临时顺序节点。),高可用(性能好,稳定可靠性高;能较好地实现阻塞式锁;支持高可用。),性能一般,安全方面断开连接,会自动释放锁
-
redis 利用 setnx 命令实现,高可用,高性能,安全方面断开连接,不会自动释放锁,需要手动释放(设置锁超时时间,到期释放)
本文主要介绍基于 Redisson 实现的 redis 分布式锁。
2. Redisson 简介
Redisson 是一个在 Redis 的基础上实现的 Java 驱动,它提供了很多分布式相关操作,其中就包含了分布式锁的实现。
Redisson 分布式锁原理:
- 可重入:利用 Hash 结构,将线程信息保存在锁的 Hash 结构中,每次加锁时判断线程是否已经持有锁,如果持有则直接返回,否则进行加锁操作。
- 可重试:利用信号量和 PubSub 机制实现锁重试机制,当获取锁失败时,通过信号量等待锁释放,当锁释放时,通过 PubSub 机制通知等待的线程重新获取锁。
- 超时续约:利用 WatchDog 机制实现锁超时续约,当锁持有超过指定时间(releaseTime / 3)时,自动续约,防止锁过期导致锁失效。
3. 基本配置
- 引入依赖
<!--redisson-->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.13.6</version>
</dependency>
- 配置链接
package com.config;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RedissonConfig {
@Bean
public RedissonClient redissonClient() {
// 配置
Config config = new Config();
config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("1234567");
// 创建RedissonClient对象
return Redisson.create(config);
}
}
- 书写测试案例
package com;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@Slf4j
@SpringBootTest
class RedissonTest {
/**
* 注入Redisson客户端
*/
@Resource
private RedissonClient redissonClient;
/**
* 注入RLock锁对象
*/
private RLock lock;
/**
* 测试前统一设置锁
*/
@BeforeEach
void setUp() {
lock = redissonClient.getLock("order");
}
}
4. 可重入锁
简单来说,就是允许同一个线程里面的多个方法同时拥有一把锁。
- 先做一个基础的测试:使用
lock.tryLock()无参。
@Test
void testLock() throws InterruptedException {
boolean lock1 = lock.tryLock();
if (lock1) {
lock.unlock();
}
}
- 在
tryLock()方法实现中,org.redisson.RedissonLock类中有一个关键实现(可使用 idea 的ctrl+点击查看实现):
其中参数为:
【等待时间】waitTime=-1
【ttl 时间】leaseTime=30*1000
【时间单位】unit=TimeUnit.MILLISECONDS
【线程 id】threadId=Thread.currentThread().getId()
【redis 操作方式】command="EVAL"使用 lua 脚本模式保证原子性操作
<T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
internalLockLeaseTime = unit.toMillis(leaseTime);
return evalWriteAsync(getName(), LongCodec.INSTANCE, command,
"if (redis.call('exists', KEYS[1]) == 0) then " +
"redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return nil; " +
"end; " +
"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
"redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return nil; " +
"end; " +
"return redis.call('pttl', KEYS[1]);",
Collections.singletonList(getName()), internalLockLeaseTime, getLockName(threadId));
}
其中关键实现为那一段 lua 脚本,其中执行 lua 脚本传递的参数解释如下:
Collections.singletonList(getName()):脚本里面的 key 参数数组,此处只传递了锁的 key 值
internalLockLeaseTime:自动释放时间 TTL
getLockName(threadId)=commandExecutor.getConnectionManager().getId() + ":" + threadId理解为当前线程的标识
local lockKey = '锁key'
local threadId = '当前线程标识' -- 应该是一个代表当前线程的唯一标识
local expireTimeMs = '过期时间' -- 毫秒
-- 是操作的Redis的Hash数据类型(这样可以使用hash的key-value模式实现可重入锁)
-- 判断锁是否存在
if (redis.call('exists', lockKey) == 0) then
-- 不存在锁就创建(Hash数据类型),设置当前线程标识,并设置过期时间(毫秒)
redis.call('hincrby', lockKey, threadId, 1);
redis.call('pexpire', lockKey, expireTimeMs);
-- 返回为空
return nil;
end
-- 存在则判断是否是当前线程拥有的锁
if (redis.call('hexists', lockKey, threadId) == 1) then
-- 存在则值加1(允许多把锁重入),并设置过期时间(毫秒)
redis.call('hincrby', lockKey, threadId, 1);
redis.call('pexpire', lockKey, expireTimeMs);
return nil;
end
-- 存在锁,但不是当前线程拥有,则返回该key的剩余过期时间(毫秒)
return redis.call('pttl', lockKey);
- 锁释放的方法中
lock.unlock();的实现为org.redisson.RedissonLock类里面的unlockInnerAsync方法。其中参数为:
【线程 id】threadId=Thread.currentThread().getId()
protected RFuture<Boolean> unlockInnerAsync(long threadId) {
return evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
"return nil;" +
"end; " +
"local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
"if (counter > 0) then " +
"redis.call('pexpire', KEYS[1], ARGV[2]); " +
"return 0; " +
"else " +
"redis.call('del', KEYS[1]); " +
"redis.call('publish', KEYS[2], ARGV[1]); " +
"return 1; " +
"end; " +
"return nil;",
Arrays.asList(getName(), getChannelName()), LockPubSub.UNLOCK_MESSAGE, internalLockLeaseTime, getLockName(threadId));
}
其中关键实现为那一段 lua 脚本,其中执行 lua 脚本传递的参数解释如下:
Arrays.asList(getName(), getChannelName()):脚本里面的 key 参数数组,此处getName()指锁的 key 值;getChannelName() = "redisson_lock__channel"+ ":{" + getName()+ "}"指锁通道名称,当锁被释放后会使用订阅发布的模式通知订阅该通道的线程重新获取锁。
LockPubSub.UNLOCK_MESSAGE = 0L解锁发布的信息。
internalLockLeaseTime:自动释放时间 TTL
getLockName(threadId)=commandExecutor.getConnectionManager().getId() + ":" + threadId理解为当前线程的标识
local lockKey = '锁key'
local threadId = '当前线程标识' -- 应该是一个代表当前线程的唯一标识
local expireTimeMs = '过期时间' -- 毫秒
-- 判断锁key的当前线程标识是否存在,不存在则返回nil,表示当前锁不是被当前线程持有
if (redis.call('hexists', lockKey, threadId) == 0) then return nil; end
-- 对持有的锁减1
local counter = redis.call('hincrby', lockKey, threadId, -1);
-- 判断锁的个数
if (counter > 0) then
-- 锁的个数大于0,表示当前锁被当前线程还在持有,更新过期时间
redis.call('pexpire', lockKey, expireTimeMs);
return 0;
else
-- 锁的个数等于0,表示当前锁已经全部被当前线程释放,删除key,并发布通知(通知其他正在等待拿取锁的线程)
redis.call('del', lockKey);
redis.call('publish', 'channel通知', 0);
return 1;
end
return nil;
5. 可重试锁
简单来说,就是运行线程有一个等待拿取锁的时间,而不是获取锁失败就直接放弃。
- 先做一个基础的测试:使用`lock.tryLock(1000L, TimeUnit.SECONDS);有参,设置等待时间为 1000 秒。
@Test
void testLock2() throws InterruptedException {
boolean lock1 = lock.tryLock(1000L, TimeUnit.SECONDS);
if (lock1) {
lock.unlock();
}
}
- 其中可重试性的关键实现在
org.redisson.RedissonLock类的tryLock方法
@Override
/**
* waitTime: 等待时间 - 此处为1000秒
* leaseTime: 锁持有时间 - 此处为-1,不设置(默认看门狗机制)
* unit: 时间单位 - 此处为秒
*/
public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
// 将等待时间转化为毫秒
long time = unit.toMillis(waitTime);
// 记录当前时间戳-为等待时间做准备
long current = System.currentTimeMillis();
// 获取当前线程的id
long threadId = Thread.currentThread().getId();
// 尝试获取锁(和上面可重入锁的原理一致) org.redisson.RedissonLock#tryAcquireAsync --> org.redisson.RedissonLock#tryLockInnerAsync
// 如果没有获取成功,则返回的是当前锁的剩余时间TTL
Long ttl = tryAcquire(waitTime, leaseTime, unit, threadId);
// lock acquired - 即获取到了锁
if (ttl == null) {
return true;
}
// 等待时间 减去 记录获取锁失败的时间 = 剩余等待时间
time -= System.currentTimeMillis() - current;
if (time <= 0) {
// 等待时间为0,则直接返回false
acquireFailed(waitTime, unit, threadId);
return false;
}
// 记录当前时间戳
current = System.currentTimeMillis();
// 订阅锁释放事件 org.redisson.RedissonLock#subscribe --> org.redisson.pubsub.PublishSubscribe#subscribe
// 其本质是使用Redis的Pub/Sub机制,订阅一个channel,当锁释放时会发布一个消息到这个channel
// 此处的channel为:redisson_lock__channel:{锁名称}
RFuture<RedissonLockEntry> subscribeFuture = subscribe(threadId);
// 订阅等待,如果超过等待时间,则取消订阅
if (!subscribeFuture.await(time, TimeUnit.MILLISECONDS)) {
if (!subscribeFuture.cancel(false)) {
subscribeFuture.onComplete((res, e) -> {
if (e == null) {
unsubscribe(subscribeFuture, threadId);
}
});
}
// 订阅失败,则直接返回false
acquireFailed(waitTime, unit, threadId);
return false;
}
// 订阅成功
try {
// 记录剩余等待时间
time -= System.currentTimeMillis() - current;
if (time <= 0) {
// 等待时间为0,则直接返回false
acquireFailed(waitTime, unit, threadId);
return false;
}
// 循环操作获取锁,此处订阅成功,也有可能锁被其他线程占用,所以需要循环获取
while (true) {
// 再次尝试获取锁
long currentTime = System.currentTimeMillis();
ttl = tryAcquire(waitTime, leaseTime, unit, threadId);
// lock acquired
if (ttl == null) {
return true;
}
// 获取锁失败,更新剩余等待时间
time -= System.currentTimeMillis() - currentTime;
if (time <= 0) {
acquireFailed(waitTime, unit, threadId);
return false;
}
// waiting for message
currentTime = System.currentTimeMillis();
// 此处判断了剩余等待时间是否大于锁的TTL,如果大于则等待TTL时间,否则通过剩余等待时间去订阅锁释放消息
if (ttl >= 0 && ttl < time) {
subscribeFuture.getNow().getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
} else {
subscribeFuture.getNow().getLatch().tryAcquire(time, TimeUnit.MILLISECONDS);
}
// 记录剩余等待时间-开始下一次循环获取锁
time -= System.currentTimeMillis() - currentTime;
if (time <= 0) {
acquireFailed(waitTime, unit, threadId);
return false;
}
}
} finally {
// 最终需要取消订阅
unsubscribe(subscribeFuture, threadId);
}
// return get(tryLockAsync(waitTime, leaseTime, unit));
}
6. 解决超时释放问题-WatchDog 机制
6.1. 获取锁时开启 WatchDog
- 在获取锁时,使用无超时释放时间的参数(
leaseTime),开启 WatchDog 机制。例如boolean lock1 = lock.tryLock(1000L, TimeUnit.SECONDS); - 在方法实现中
org.redisson.RedissonLock#tryAcquireOnceAsync里面:
/*
此处waitTime表示等待获取锁的时间
leaseTime就是超时释放时间,默认-1
*/
private RFuture<Boolean> tryAcquireOnceAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId) {
if (leaseTime != -1) {
return tryLockInnerAsync(waitTime, leaseTime, unit, threadId, RedisCommands.EVAL_NULL_BOOLEAN);
}
// 默认leaseTime = -1,设置默认超时时间,并开启WatchDog机制
// 默认超时时间为commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout() = 30秒
RFuture<Boolean> ttlRemainingFuture = tryLockInnerAsync(waitTime,
commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(),
TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_NULL_BOOLEAN);
// 当获取锁结束之后执行
ttlRemainingFuture.onComplete((ttlRemaining, e) -> {
if (e != null) {
return;
}
// 此处做了一个判断,看是否获取锁成功
// lock acquired
if (ttlRemaining) {
// 获取锁成功则开启定时刷新超时时间的机制(参数为线程id)
scheduleExpirationRenewal(threadId);
}
});
return ttlRemainingFuture;
}
- 跟踪上述
scheduleExpirationRenewal(threadId);方法org.redisson.RedissonLock#scheduleExpirationRenewal
方法里面EXPIRATION_RENEWAL_MAP为一个 map,getEntryName() = commandExecutor.getConnectionManager().getId() + ":" + name为线程标识+锁的名称
private static final ConcurrentMap<String, ExpirationEntry> EXPIRATION_RENEWAL_MAP = new ConcurrentHashMap<>();
private void scheduleExpirationRenewal(long threadId) {
ExpirationEntry entry = new ExpirationEntry();
// 在map里面添加当前线程锁的ExpirationEntry
ExpirationEntry oldEntry = EXPIRATION_RENEWAL_MAP.putIfAbsent(getEntryName(), entry);
if (oldEntry != null) {
oldEntry.addThreadId(threadId);
} else {
entry.addThreadId(threadId);
// 当有新的线程锁时,就开启刷新机制
renewExpiration();
}
}
- 跟踪
renewExpiration()方法,org.redisson.RedissonLock#renewExpiration
定时任务时间为internalLockLeaseTime / 3 = 30秒/3 = 10秒
大致任务就是每隔 10 秒会触发刷新释放时间 TTL。
private void renewExpiration() {
ExpirationEntry ee = EXPIRATION_RENEWAL_MAP.get(getEntryName());
if (ee == null) {
return;
}
// 此处就开启一个定时任务:任务内容+时间
Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
@Override
public void run(Timeout timeout) throws Exception {
// 在Map里面获取储存的当前线程锁ExpirationEntry
ExpirationEntry ent = EXPIRATION_RENEWAL_MAP.get(getEntryName());
if (ent == null) {
return;
}
// 获取线程id
Long threadId = ent.getFirstThreadId();
if (threadId == null) {
return;
}
// 开始执行刷新超时时间的人物
RFuture<Boolean> future = renewExpirationAsync(threadId);
future.onComplete((res, e) -> {
if (e != null) {
log.error("Can't update lock " + getName() + " expiration", e);
return;
}
// 刷新成功后,重调renewExpiration方法。循环执行
if (res) {
// reschedule itself
renewExpiration();
}
});
}
}, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS);
ee.setTimeout(task);
}
- 跟踪方法
renewExpirationAsync(threadId),org.redisson.RedissonLock#renewExpirationAsync
其中 lua 传递参数
Collections.singletonList(getName()) = 锁的名称
internalLockLeaseTime = TTL时间
getLockName(threadId) = 当前线程标识+线程id
protected RFuture<Boolean> renewExpirationAsync(long threadId) {
return evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
"if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
"redis.call('pexpire', KEYS[1], ARGV[1]); " +
"return 1; " +
"end; " +
"return 0;",
Collections.singletonList(getName()),
internalLockLeaseTime, getLockName(threadId));
}
关键为那一段 Lua 脚本:
local lockKey = '锁key'
local threadId = '当前线程标识' -- 应该是一个代表当前线程的唯一标识
local expireTimeMs = '过期时间' -- 毫秒
-- 判断锁是否由当前线程持有
if (redis.call('hexists', lockKey, threadId) == 1) then
-- 持有锁则更新锁的过期时间
redis.call('pexpire', lockKey, expireTimeMs);
return 1;
end
return 0;
6.2. 释放锁时关闭 WatchDog
- 释放锁后关键代码为
org.redisson.RedissonLock#unlockAsync(long)
@Override
public RFuture<Void> unlockAsync(long threadId) {
RPromise<Void> result = new RedissonPromise<Void>();
// 释放锁
RFuture<Boolean> future = unlockInnerAsync(threadId);
future.onComplete((opStatus, e) -> {
// 释放锁成功后取消定时刷新任务
cancelExpirationRenewal(threadId);
if (e != null) {
result.tryFailure(e);
return;
}
if (opStatus == null) {
IllegalMonitorStateException cause = new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: "
+ id + " thread-id: " + threadId);
result.tryFailure(cause);
return;
}
result.trySuccess(null);
});
return result;
}
- 跟踪
cancelExpirationRenewal(threadId);方法org.redisson.RedissonLock#cancelExpirationRenewal
void cancelExpirationRenewal(Long threadId) {
// 获取Map中当前线程锁的任务
// getEntryName() = 当前线程标识 + 锁名称
ExpirationEntry task = EXPIRATION_RENEWAL_MAP.get(getEntryName());
if (task == null) {
return;
}
// 删除当前任务的线程id,这里的删除不是简单的delete。
// 参考下面的方法解读org.redisson.RedissonLock.ExpirationEntry#removeThreadId
if (threadId != null) {
task.removeThreadId(threadId);
}
// 判断是否无线程id了,判断是否锁已经全部释放
if (threadId == null || task.hasNoThreads()) {
// 获取定时刷新超时时间的任务
Timeout timeout = task.getTimeout();
if (timeout != null) {
// 取消任务
timeout.cancel();
}
// 同时删除Map里面存放的当前线程锁标识
EXPIRATION_RENEWAL_MAP.remove(getEntryName());
}
}
- 跟踪
task.removeThreadId(threadId);方法:删除线程 idorg.redisson.RedissonLock.ExpirationEntry#removeThreadId
这里其实是查看当前线程锁被重入了几次,一次一次的释放。
public synchronized void removeThreadId(long threadId) {
// 获取线程id获取锁的计数器
Integer counter = threadIds.get(threadId);
if (counter == null) {
return;
}
// 释放锁就减1
counter--;
// 如果没有锁了,就删除线程id
if (counter == 0) {
threadIds.remove(threadId);
} else {
threadIds.put(threadId, counter);
}
}
1704

被折叠的 条评论
为什么被折叠?



