• 深入了解Redission分布式锁原理以及可重入锁的原理


    Redisson是一个基于Redis的Java框架,用于实现各种分布式功能,包括分布式锁。Redisson提供了多种分布式锁的实现,其中包括可重入锁、公平锁、联锁(多个锁同时锁定或释放)、红锁(多个独立Redis节点的分布式锁),以及读写锁等。


    基于setnx实现的分布式锁存在以下四个问题

    Redisson入门使用教程 

    Redisson客户端配置:首先,您需要配置Redisson客户端以连接到Redis服务器。通常,这涉及创建一个Config对象,并使用useSingleServer()或其他方法指定Redis服务器的连接信息。示例代码中的配置是连接到本地Redis服务器的示例。(对了这里不要忘记引入redisson依赖)

    1. Config config = new Config();
    2. config.useSingleServer().setAddress("redis://localhost:6379").setPassword("your word");
    3. return Redisson.create(config)

     Redisson的使用

    1. public class RedissonLockExample {
    2. public static void main(String[] args) {
    3. // 配置Redisson
    4. Config config = new Config();
    5. config.useSingleServer().setAddress("redis://localhost:6379");
    6. // 创建Redisson客户端
    7. RedissonClient redisson = Redisson.create(config);
    8. // 获取锁
    9. RLock lock = redisson.getLock("myLock");
    10. try {
    11. // 尝试加锁,最多等待10秒
    12. boolean locked = lock.tryLock(10, 30, java.util.concurrent.TimeUnit.SECONDS);
    13. if (locked) {
    14. // 锁定成功,执行需要加锁的代码
    15. System.out.println("获取锁成功,这里来写需要加锁的代码");
    16. Thread.sleep(5000); // 模拟锁定后的操作
    17. } else {
    18. // 锁定失败
    19. System.out.println("获取锁失败");
    20. }
    21. } catch (InterruptedException e) {
    22. e.printStackTrace();
    23. } finally {
    24. // 释放锁
    25. lock.unlock();
    26. System.out.println("释放锁");
    27. }
    28. // 关闭Redisson客户端
    29. redisson.shutdown();
    30. }

     深入讲解Redisson可重入锁的工作原理

     重入锁原理 

          重入锁(Reentrant Lock)是一种高级的同步工具,它允许同一个线程多次获取同一把锁,而不会发生死锁。这意味着一个线程在持有锁的情况下可以多次进入锁保护的代码块,而不会被自己阻塞

    1. 锁计数器:重入锁内部维护一个锁计数器,用于跟踪锁的持有次数。初始时,锁计数器为0,表示没有线程持有该锁。

    2. 加锁操作:当一个线程首次请求加锁时,锁计数器会增加,同时记录下持有锁的线程。此时,线程获得了锁,并且可以执行锁保护的代码块。

    3. 重入:如果同一个线程再次请求加锁(重复加锁),锁计数器会继续增加,表示锁被持有多次。线程在退出锁保护的代码块之前,可以多次加锁和解锁,而锁计数器会相应地增加和减少。

    4. 解锁操作:每次线程解锁时,锁计数器减少。只有当锁计数器减少为0时,锁才会被完全释放,其他线程才有机会获得锁。

    作用:

    1. 避免死锁:重入锁允许同一线程多次获取锁,因此不会因为线程自己持有的锁而导致死锁。这在复杂的多线程场景中非常有用,因为线程可能需要在执行一些递归函数或者多层嵌套的方法时多次获取锁。

    2. 精细控制锁的释放:与传统的synchronized关键字相比,重入锁允许更灵活地控制锁的释放。线程可以在锁保护的代码块内多次获取和释放锁,而不必将整个代码块包裹在同一个synchronized块中。

    我们来看一下trylock的底层逻辑:

     通过redis的hash结构来实现锁的重入,如果第一次获取锁就创建,并把value设置为1,再次有线程想要获取锁就再次增加value的值,释放锁时每当一个线程释放时value就减一。直到为0彻底释放完成

    调用了tryLockAsync方法并传入了线程id的参数

     由于初始时未填写过期时间等待时间等信息,默认为-1,进而再次调用tryAcquireOnceAsync方法

    1. RFuture tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand command) {
    2. this.internalLockLeaseTime = unit.toMillis(leaseTime);
    3. return this.evalWriteAsync(this.getName(), LongCodec.INSTANCE, command,
    4. "if (redis.call('exists', KEYS[1]) == 0) then
    5. redis.call('hincrby', KEYS[1], ARGV[2], 1);
    6. redis.call('pexpire', KEYS[1], ARGV[1]);
    7. return nil; end;
    8. if (redis.call('hexists', KEYS[1], ARGV[2]) == 1)
    9. then redis.call('hincrby', KEYS[1], ARGV[2], 1);
    10. redis.call('pexpire', KEYS[1], ARGV[1]);
    11. return nil; end;
    12. return redis.call('pttl', KEYS[1]);",
    13. Collections.singletonList(this.getName()), this.internalLockLeaseTime, this.getLockName(threadId));
    14. }

    可见为了保证获取锁的原子性也即不让其他线程在这个线程获取锁的过程中“插队”执行需要将获取锁的代码写入一个Lua脚本当中。

    当==0时表示之前未有线程获取锁创建并赋值。当==1时表示存在,为了实现重入就在value上加一,并设置过期时间。注意 这里返回nil代表成功,失败返回对应的时间毫秒值pttl

    之后会释放锁

    1. protected RFuture unlockInnerAsync(long threadId) {
    2. return this.evalWriteAsync(this.getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then return nil;end;
    3. local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); if (counter > 0) then redis.call('pexpire', KEYS[1], ARGV[2]); return 0;
    4. else redis.call('del', KEYS[1]); redis.call('publish', KEYS[2], ARGV[1]); return 1; end; return nil;",
    5. Arrays.asList(this.getName(), this.getChannelName()), LockPubSub.UNLOCK_MESSAGE, this.internalLockLeaseTime, this.getLockName(threadId));
    6. }

    每次释放锁都会对数量减一直至0,并且发布释放锁的通知

    重试获取锁机制讲解

    trylock源码

    1. public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
    2. long time = unit.toMillis(waitTime);
    3. long current = System.currentTimeMillis();
    4. long threadId = Thread.currentThread().getId();
    5. Long ttl = this.tryAcquire(waitTime, leaseTime, unit, threadId);
    6. if (ttl == null) {
    7. return true;
    8. } else {
    9. time -= System.currentTimeMillis() - current;
    10. if (time <= 0L) {
    11. this.acquireFailed(waitTime, unit, threadId);
    12. return false;
    13. } else {
    14. current = System.currentTimeMillis();
    15. RFuture subscribeFuture = this.subscribe(threadId);
    16. if (!subscribeFuture.await(time, TimeUnit.MILLISECONDS)) {
    17. if (!subscribeFuture.cancel(false)) {
    18. subscribeFuture.onComplete((res, e) -> {
    19. if (e == null) {
    20. this.unsubscribe(subscribeFuture, threadId);
    21. }
    22. });
    23. }
    24. this.acquireFailed(waitTime, unit, threadId);
    25. return false;
    26. } else {
    27. try {
    28. time -= System.currentTimeMillis() - current;
    29. if (time <= 0L) {
    30. this.acquireFailed(waitTime, unit, threadId);
    31. boolean var20 = false;
    32. return var20;
    33. } else {
    34. boolean var16;
    35. do {
    36. long currentTime = System.currentTimeMillis();
    37. ttl = this.tryAcquire(waitTime, leaseTime, unit, threadId);
    38. if (ttl == null) {
    39. var16 = true;
    40. return var16;
    41. }
    42. time -= System.currentTimeMillis() - currentTime;
    43. if (time <= 0L) {
    44. this.acquireFailed(waitTime, unit, threadId);
    45. var16 = false;
    46. return var16;
    47. }
    48. currentTime = System.currentTimeMillis();
    49. if (ttl >= 0L && ttl < time) {
    50. ((RedissonLockEntry)subscribeFuture.getNow()).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
    51. } else {
    52. ((RedissonLockEntry)subscribeFuture.getNow()).getLatch().tryAcquire(time, TimeUnit.MILLISECONDS);
    53. }
    54. time -= System.currentTimeMillis() - currentTime;
    55. } while(time > 0L);
    56. this.acquireFailed(waitTime, unit, threadId);
    57. var16 = false;
    58. return var16;
    59. }
    60. } finally {
    61. this.unsubscribe(subscribeFuture, threadId);
    62. }
    63. }
    64. }
    65. }
    66. }

    可见这里默认ttl也是为-1,注意tryAcquire方法,返回值为ttl,ttl为null即为获得锁成功

    这里由于默认存活时间为-1,所以下面参数默认存活时间为

    this.commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout()
    

    (watchdog看门狗)也就是30s。

    如果ttl为null那么返回true代表获取成功

    否则用最大等待时间time减去上面的系统时间算出这段代码的耗时,如果为负数说明超过最大等待时长,返回false,如果time大于0,不直接判断,因为此时别的线程获取锁正在执行,假设立马执行只是会浪费cpu资源,所以这里用了subscribe(threadId)方法来订阅锁释放的信息(上面的unlock代码释放锁会发布信息),然后采用计数器进行等待,等待时长为time,假设没等到,返回false,那么使用unsubscribe()方法结束订阅,返回false。

    如果等到别的线程释放锁,就再次判断上面代码是否超时,超时返回false,否则再次带哦用tryAcquire方法

    如果ttl小于等待时间time,那么就尝试ttl时间,否则就尝试获取锁在time时间内,知道time结束,这就时重试获取锁机制了。


    Redisson分布式锁的原理

    获取锁

    也就是说如果不设置存活时间,那么会利用看门狗执行任务刷新等待

    释放锁 

  • 相关阅读:
    C语言字符函数和字符串函数详解
    springboot学习二:springboot 初创建 web 项目,打包项目并测试成功
    详解利用高斯混合模型拆解多模态分布 + 精美可视化
    js单行文本溢出显示省略号时才展示el-tooltip
    【功能测试】-【黑盒测试用例】
    大数据知识面试题-通用(2022版)
    微信小程序:(更新)云开发微群人脉
    Linux与Shell学习--shell系列3--变量
    微服务从代码到k8s部署应有尽有系列(十三、服务监控)
    助推智慧民航,美创亮相全国民航“互联网+”智慧机场建设发展高峰会
  • 原文地址:https://blog.csdn.net/Qstar666/article/details/134272568