Redis分布式锁,看完不懂你打我,2024蚂蚁金服Java面试真题解析

this.commandExecutor = commandExecutor;

//uuid

this.id = commandExecutor.getConnectionManager().getId();

//超时时间,默认30s

this.internalLockLeaseTime = commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout();

this.entryName = id + “:” + name;

}

public void lockInterruptibly(long leaseTime, TimeUnit unit) throws InterruptedException {

//获取线程id

long threadId = Thread.currentThread().getId();

//尝试获取锁

Long ttl = tryAcquire(leaseTime, unit, threadId);

// lock acquired

//ttl为空则代表加锁成功

if (ttl == null) {

return;

}

//如果获取锁失败,则订阅到对应这个锁的channel,等其他线程释放锁时,通知线程去获取锁

RFuture future = subscribe(threadId);

commandExecutor.syncSubscription(future);

try {

while (true) {

//再次尝试获取锁

ttl = tryAcquire(leaseTime, unit, threadId);

// lock acquired

if (ttl == null) {

break;

}

// waiting for message

//ttl大于0,则等待ttl时间后继续尝试获取锁

if (ttl >= 0) {

getEntry(threadId).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);

} else {

getEntry(threadId).getLatch().acquire();

}

}

} finally {

//取消对channel的订阅

unsubscribe(future, threadId);

}

// get(lockAsync(leaseTime, unit));

}

再来看看里面的尝试获取锁的代码:

private Long tryAcquire(long leaseTime, TimeUnit unit, long threadId) {

return get(tryAcquireAsync(leaseTime, unit, threadId));

}

private RFuture tryAcquireAsync(long leaseTime, TimeUnit unit, final long threadId) {

if (leaseTime != -1) {

//如果带有过期时间,则按照普通方式获取锁

return tryLockInnerAsync(leaseTime, unit, threadId, RedisCommands.EVAL_LONG);

}

//先按照30秒的过期时间来执行获取锁的方法

RFuture ttlRemainingFuture = tryLockInnerAsync(commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout(), TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);

//异步执行回调监听

ttlRemainingFuture.addListener(new FutureListener() {

@Override

//如果还持有这个锁,则开启定时任务不断刷新该锁的过期时间

public void operationComplete(Future future) throws Exception {

//没有成功执行完成

if (!future.isSuccess()) {

return;

}

//非阻塞地返回异步结果,如果尚未完成返回null

Long ttlRemaining = future.getNow();

// lock acquired

if (ttlRemaining == null) {

scheduleExpirationRenewal(threadId);

}

}

});

return ttlRemainingFuture;

}

看门狗逻辑:

使用的是Netty的Timeout延迟任务做的。

  • 比如锁过期 30 秒, 每过 1/3 时间也就是 10 秒会检查锁是否存在, 存在则更新锁的超时时间

加锁脚本

RFuture tryLockInnerAsync(long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand command) {

internalLockLeaseTime = unit.toMillis(leaseTime);

return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, command,

//如果锁不存在,则通过hset设置它的值,并设置过期时间

"if (redis.call(‘exists’, KEYS[1]) == 0) then " +

"redis.call(‘hset’, KEYS[1], ARGV[2], 1); " +

"redis.call(‘pexpire’, KEYS[1], ARGV[1]); " +

"return nil; " +

"end; " +

//如果锁已存在,并且锁的是当前线程,则通过hincrby给数值递增1,并重新设置过期时间

"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));

}

解锁:

public RFuture unlockAsync(final long threadId) {

final RPromise result = new RedissonPromise();

//底层解锁方法

RFuture future = unlockInnerAsync(threadId);

future.addListener(new FutureListener() {

@Override

public void operationComplete(Future future) throws Exception {

if (!future.isSuccess()) {

cancelExpirationRenewal(threadId);

result.tryFailure(future.cause());

return;

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Java工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Java开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Java开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip1024b (备注Java)
img

最后

权威指南-第一本Docker书

引领完成Docker的安装、部署、管理和扩展,让其经历从测试到生产的整个开发生命周期,深入了解Docker适用于什么场景。并且这本Docker的学习权威指南介绍了其组件的基础知识,然后用Docker构建容器和服务来完成各种任务:利用Docker为新项目建立测试环境,演示如何使用持续集成的工作流集成Docker,如何构建应用程序服务和平台,如何使用Docker的API,如何扩展Docker。

总共包含了:简介、安装Docker、Docker入门、使用Docker镜像和仓库、在测试中使用Docker、使用Docker构建服务、使用Fig编配Docke、使用Docker API、获得帮助和对Docker进行改进等9个章节的知识。

image

image

image

image

关于阿里内部都在强烈推荐使用的“K8S+Docker学习指南”—《深入浅出Kubernetes:理论+实战》、《权威指南-第一本Docker书》,看完之后两个字形容,爱了爱了!
使用Docker API、获得帮助和对Docker进行改进等9个章节的知识。

[外链图片转存中…(img-znPE9eur-1711783163210)]

[外链图片转存中…(img-3q4tPCFO-1711783163211)]

[外链图片转存中…(img-zKvn7tHz-1711783163211)]

[外链图片转存中…(img-5qmG38sW-1711783163212)]

关于阿里内部都在强烈推荐使用的“K8S+Docker学习指南”—《深入浅出Kubernetes:理论+实战》、《权威指南-第一本Docker书》,看完之后两个字形容,爱了爱了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值