redis 分布式重入锁

[复制链接]
发表于 2025-11-8 00:03:02 | 显示全部楼层 |阅读模式

媒介

通过前篇文章 redis 分布式锁实现
我们发现简朴做一把分布式锁没啥标题,但是针对以往的锁来说,还存在一下两点必要思量。


  • 1.一个线程如果多次重复拿锁,该怎样实现重入
  • 2.由于防止死锁设置了逾期时间,那么如果锁的时间到期了,业务还没有实行完毕,导致新的业务进来造成的并发标题如那边理

一、分布式重入锁

1、单机重入锁

在单机锁期间,必要支持重入告急是为了制止在单线程环境下大概出现的死锁标题,同时简化编程模子,提升代码的机动性与可重用性。


  • 制止死锁:如果一个线程在持有锁的环境下,再次实行获取同一把锁,非重入锁会导致该线程不停等候自己开释锁,从而引发死锁标题。重入锁答应同一个线程多次获取同一把锁,如许就可以制止这种环境的发生。
  • 简化递归调用场景:在递归方法中,方法会多次调用自己,而每次调用都必要通过同一个锁掩护共享资源。重入锁可以或许确保这些调用不会由于锁的重复获取而出现壅闭环境。
  • 支持锁的调用链:在面向对象编程中,一个持有锁的方法大概会调用对象中同样必要持有锁的其他方法。重入锁包管这些方法可以顺遂实行而不会由于锁的竞争而壅闭。
  • 加强机动性:重入锁数据布局更复杂,可以纪录获取锁的次数。这使得锁可以机动用在较复杂的同步场景中。
    综上所述,重入锁通过答应同一线程多次获取同一把锁,制止了很多潜伏的同步标题,使得同步代码的编写变得更加简朴和可靠。
比方synchronized、ReentrantLock
2、redis重入锁

参考重入锁的筹划头脑,我们在实现redis重入锁,应该要遵照一下原则


  • 互斥条件:实现锁的须要条件,标记是否有线程已占用,差别线程不能重复占用
  • 线程信息:纪录线程信息,来判定加锁的是不是同一个线程
  • 重入次数:纪录重入次数,再开释锁的时间,淘汰相应的次数
二、redisson实现重入锁

1、 添加依赖

  1. <dependency>
  2.     <groupId>org.redisson</groupId>
  3.     <artifactId>redisson-spring-boot-starter</artifactId>
  4.     <version>3.16.3</version> <!-- 根据需要选择合适的版本 -->
  5. </dependency>
复制代码
2、 设置 Redisson 客户端

平凡模式
  1. import org.redisson.Redisson;
  2. import org.redisson.api.RedissonClient;
  3. import org.redisson.config.Config;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. @Configuration
  7. public class RedissonConfig {
  8.     @Bean
  9.     public RedissonClient redissonClient() {
  10.         Config config = new Config();
  11.         config.useSingleServer()
  12.                 .setAddress("redis://127.0.0.1:6379");
  13.         return Redisson.create(config);
  14.     }
  15. }
复制代码
集群模式
  1. @Bean
  2. public RedissonClient redissonClient() {
  3.     Config config = new Config();
  4.     config.useClusterServers()
  5.         .addNodeAddress("redis://127.0.0.1:7000", "redis://127.0.0.1:7001");
  6.     return Redisson.create(config);
  7. }
复制代码
哨兵模式
  1. @Bean
  2. public RedissonClient redissonClient() {
  3.     Config config = new Config();
  4.     config.useSentinelServers()
  5.             .setMasterName("masterName")
  6.             .addSentinelAddress("redis://127.0.0.1:26379", "redis://127.0.0.1:26380");
  7.     return Redisson.create(config);
  8. }
复制代码
3、 使用 Redisson 实现重入锁

  1. import org.redisson.api.RLock;
  2. import org.redisson.api.RedissonClient;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. @Service
  6. public class MyService {
  7.     @Autowired
  8.     private RedissonClient redissonClient;
  9.     private String lock = "myLock";
  10.     public void outerMethod() {
  11.         RLock lock = redissonClient.getLock(lock);
  12.         lock.lock();
  13.         try {
  14.             System.out.println("Outer method acquired lock");
  15.             innerMethod();
  16.         } finally {
  17.             lock.unlock();
  18.             System.out.println("Outer method released lock");
  19.         }
  20.     }
  21.     private void innerMethod() {
  22.         RLock lock = redissonClient.getLock(lock);
  23.         lock.lock();
  24.         try {
  25.             System.out.println("Inner method acquired lock");
  26.         } finally {
  27.             lock.unlock();
  28.             System.out.println("Inner method released lock");
  29.         }
  30.     }
  31. }
复制代码
4、 验证

  1. import org.springframework.beans.factory.annotation.Autowired;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. public class MyController {
  6.     @Autowired
  7.     private MyService myService;
  8.     @GetMapping("/test-lock")
  9.     public String testLock() {
  10.         myService.outerMethod();
  11.         return "Lock tested successfully";
  12.     }
  13. }
复制代码
5、运行项目

启动 Spring Boot 应用,并访问 http://localhost:8080/test-lock 以测试多次重入锁的实现。你应该可以或许在控制台上看到如下输出,表明锁多次重入的准确实行:
  1. Outer method acquired lock
  2. Inner method acquired lock
  3. Inner method released lock
  4. Outer method released lock
复制代码
三、redisson分布式锁分析

1、获取锁对象

  1. RLock lock = redissonClient.getLock(lock);
  2. public RLock getLock(String name) {
  3.   return new RedissonLock(this.connectionManager.getCommandExecutor(), name, this.id);
  4. }
  5. public RedissonLock(CommandAsyncExecutor commandExecutor, String name) {
  6.   super(commandExecutor, name);
  7.   this.commandExecutor = commandExecutor;
  8.   this.internalLockLeaseTime = commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout();
  9.   this.pubSub = commandExecutor.getConnectionManager().getSubscribeService().getLockPubSub();
  10. }
  11. public RedissonBaseLock(CommandAsyncExecutor commandExecutor, String name) {
  12.   super(commandExecutor, name);
  13.   this.commandExecutor = commandExecutor;
  14.   this.id = commandExecutor.getConnectionManager().getId();
  15.   // 默认锁释放时间 30s
  16.   this.internalLockLeaseTime = commandExecutor.getConnectionManager().getCfg().getLockWatchdogTimeout();
  17.   this.entryName = id + ":" + name;
  18. }
  19. public RedissonObject(Codec codec, CommandAsyncExecutor commandExecutor, String name) {
  20.   this.codec = codec;
  21.   this.commandExecutor = commandExecutor;
  22.   if (name == null) {
  23.     throw new NullPointerException("name can't be null");
  24.   }
  25.   setName(name);
  26. }
复制代码
2、 加锁

org.redisson.RedissonLock#tryLock
  1.     @Override
  2.     public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
  3.         // 等待时间转成MS
  4.         long time = unit.toMillis(waitTime);
  5.         long current = System.currentTimeMillis();
  6.         // 当前线程
  7.         long threadId = Thread.currentThread().getId();
  8.         // 尝试获取锁 返回空标识回去锁
  9.         Long ttl = tryAcquire(waitTime, leaseTime, unit, threadId);
  10.         // lock acquired
  11.         if (ttl == null) {
  12.             return true;
  13.         }
  14.         
  15.         time -= System.currentTimeMillis() - current;
  16.         // 超时,拿锁失败 返回false
  17.         if (time <= 0) {
  18.             acquireFailed(waitTime, unit, threadId);
  19.             return false;
  20.         }
  21.         
  22.         current = System.currentTimeMillis();
  23.         // 订阅解锁消息,见org.redisson.pubsub.LockPubSub#onMessage
  24.         // 订阅锁释放事件,并通过await方法阻塞等待锁释放,有效的解决了无效的锁申请浪费资源的问题:
  25.         // 基于信息量,当锁被其它资源占用时,当前线程通过 Redis 的 channel 订阅锁的释放事件,一旦锁释放会发消息通知待等待的线程进行竞争
  26.         // 当 this.await返回false,说明等待时间已经超出获取锁最大等待时间,取消订阅并返回获取锁失败
  27.         // 当 this.await返回true,进入循环尝试获取锁
  28.         CompletableFuture<RedissonLockEntry> subscribeFuture = subscribe(threadId);
  29.         try {
  30.             subscribeFuture.get(time, TimeUnit.MILLISECONDS);
  31.         } catch (TimeoutException e) {
  32.             if (!subscribeFuture.cancel(false)) {
  33.                 subscribeFuture.whenComplete((res, ex) -> {
  34.                     if (ex == null) {
  35.                         unsubscribe(res, threadId);
  36.                     }
  37.                 });
  38.             }
  39.             acquireFailed(waitTime, unit, threadId);
  40.             return false;
  41.         } catch (ExecutionException e) {
  42.             acquireFailed(waitTime, unit, threadId);
  43.             return false;
  44.         }
  45.         try {
  46.             time -= System.currentTimeMillis() - current
  47.             // 超时,拿锁失败 返回false;
  48.             if (time <= 0) {
  49.                 acquireFailed(waitTime, unit, threadId);
  50.                 return false;
  51.             }
  52.             // 自旋获取锁
  53.             while (true) {
  54.                 long currentTime = System.currentTimeMillis();
  55.                 // 再次加锁
  56.                 ttl = tryAcquire(waitTime, leaseTime, unit, threadId);
  57.                 // lock acquired
  58.                 // 获得锁
  59.                 if (ttl == null) {
  60.                     return true;
  61.                 }
  62.                 time -= System.currentTimeMillis() - currentTime;
  63.                 // 超时,拿锁失败 返回false;
  64.                 if (time <= 0) {
  65.                     acquireFailed(waitTime, unit, threadId);
  66.                     return false;
  67.                 }
  68.                 // waiting for message
  69.                 currentTime = System.currentTimeMillis();
  70.                 // 下面的阻塞会在释放锁的时候,通过订阅发布及时relase
  71.                 if (ttl >= 0 && ttl < time) {
  72.                     // 如果锁的超时时间小于等待时间,通过SemaphorerelaseryAcquire阻塞锁的释放时间
  73.                     commandExecutor.getNow(subscribeFuture).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
  74.                 } else {
  75.                     // 否则,通过Semaphore的tryAcquire阻塞传入的最大等待时间
  76.                     commandExecutor.getNow(subscribeFuture).getLatch().tryAcquire(time, TimeUnit.MILLISECONDS);
  77.                 }
  78.                 time -= System.currentTimeMillis() - currentTime;
  79.                 if (time <= 0) {
  80.                     acquireFailed(waitTime, unit, threadId);
  81.                     return false;
  82.                 }
  83.             }
  84.         } finally {
  85.             // 取消订阅
  86.             unsubscribe(commandExecutor.getNow(subscribeFuture), threadId);
  87.         }
  88.     }
复制代码
实行获取锁
  1.     private Long tryAcquire(long waitTime, long leaseTime, TimeUnit unit, long threadId) {
  2.         return get(tryAcquireAsync(waitTime, leaseTime, unit, threadId));
  3.     }
  4.     private <T> RFuture<Long> tryAcquireAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId) {
  5.       RFuture<Long> ttlRemainingFuture;
  6.       if (leaseTime > 0) {
  7.         // 释放时间同步
  8.         ttlRemainingFuture = tryLockInnerAsync(waitTime, leaseTime, unit, threadId, RedisCommands.EVAL_LONG);
  9.       } else {
  10.         // 如果没有传入锁的释放时间,默认 internalLockLeaseTime = 30000 MS
  11.         ttlRemainingFuture = tryLockInnerAsync(waitTime, internalLockLeaseTime,
  12.                 TimeUnit.MILLISECONDS, threadId, RedisCommands.EVAL_LONG);
  13.       }
  14.       CompletionStage<Long> f = ttlRemainingFuture.thenApply(ttlRemaining -> {
  15.         // lock acquired
  16.         // 如果返回null说明抢到了锁或者是可重入 否则直接返回还有多久过期
  17.         if (ttlRemaining == null) {
  18.           if (leaseTime > 0) {
  19.             // 释放时间 赋值给 internalLockLeaseTime
  20.             internalLockLeaseTime = unit.toMillis(leaseTime);
  21.           } else {
  22.             scheduleExpirationRenewal(threadId);
  23.           }
  24.         }
  25.         // 没有抢到直接返回
  26.         return ttlRemaining;
  27.       });
  28.       return new CompletableFutureWrapper<>(f);
  29.     }
  30.     <T> RFuture<T> tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand<T> command) {
  31.       return evalWriteAsync(getRawName(), LongCodec.INSTANCE, command,
  32.               
  33.               "if (redis.call('exists', KEYS[1]) == 0) then " +
  34.                       "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
  35.                       "redis.call('pexpire', KEYS[1], ARGV[1]); " +
  36.                       "return nil; " +
  37.                       "end; " +
  38.                       "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
  39.                       "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
  40.                       "redis.call('pexpire', KEYS[1], ARGV[1]); " +
  41.                       "return nil; " +
  42.                       "end; " +
  43.                       "return redis.call('pttl', KEYS[1]);",
  44.               Collections.singletonList(getRawName()), unit.toMillis(leaseTime), getLockName(threadId));
  45.     }
复制代码
LUA脚天职析
  1. # 加锁
  2. "if (redis.call('exists', KEYS[1]) == 0) then " # 判断我的锁是否存在 =0 为不存在 没人抢占锁
  3. "redis.call('hincrby', KEYS[1], ARGV[2], 1); " + # 设置锁并计数重入次数
  4. "redis.call('pexpire', KEYS[1], ARGV[1]); " + # 设置过期时间 30S
  5. "return nil; " +
  6. "end; " +
  7. # 重入
  8. "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " + # 进入该逻辑说明有线程抢占了锁 继续判断是否同一个线程 ==1 为同一线程
  9. "redis.call('hincrby', KEYS[1], ARGV[2], 1); " + # 重入次数 + 1
  10. "redis.call('pexpire', KEYS[1], ARGV[1]); " + # 设置超时时间
  11. "return nil; " +
  12. "end; " +
  13. "return redis.call('pttl', KEYS[1]);", // 前面2个if都没进,说明锁被抢占并且不是同一线程,直接返回过期时间
复制代码
3、订阅

订阅锁状态,挂起叫醒线程
org.redisson.RedissonLock#subscribe
  1. public CompletableFuture<E> subscribe(String entryName, String channelName) {
  2.         AsyncSemaphore semaphore = service.getSemaphore(new ChannelName(channelName));
  3.         CompletableFuture<E> newPromise = new CompletableFuture<>();
  4.         semaphore.acquire().thenAccept(c -> {
  5.             if (newPromise.isDone()) {
  6.                 semaphore.release();
  7.                 return;
  8.             }
  9.             E entry = entries.get(entryName);
  10.             if (entry != null) {
  11.                 entry.acquire();
  12.                 semaphore.release();
  13.                 entry.getPromise().whenComplete((r, e) -> {
  14.                     if (e != null) {
  15.                         newPromise.completeExceptionally(e);
  16.                         return;
  17.                     }
  18.                     newPromise.complete(r);
  19.                 });
  20.                 return;
  21.             }
  22.             E value = createEntry(newPromise);
  23.             value.acquire();
  24.             E oldValue = entries.putIfAbsent(entryName, value);
  25.             if (oldValue != null) {
  26.                 oldValue.acquire();
  27.                 semaphore.release();
  28.                 oldValue.getPromise().whenComplete((r, e) -> {
  29.                     if (e != null) {
  30.                         newPromise.completeExceptionally(e);
  31.                         return;
  32.                     }
  33.                     newPromise.complete(r);
  34.                 });
  35.                 return;
  36.             }
  37.             // 创建监听,释放锁,会发送消息
  38.             RedisPubSubListener<Object> listener = createListener(channelName, value);
  39.             CompletableFuture<PubSubConnectionEntry> s = service.subscribeNoTimeout(LongCodec.INSTANCE, channelName, semaphore, listener);
  40.             newPromise.whenComplete((r, e) -> {
  41.                 if (e != null) {
  42.                     s.completeExceptionally(e);
  43.                 }
  44.             });
  45.             s.whenComplete((r, e) -> {
  46.                 if (e != null) {
  47.                     value.getPromise().completeExceptionally(e);
  48.                     return;
  49.                 }
  50.                 value.getPromise().complete(value);
  51.             });
  52.         });
  53.         return newPromise;
  54.     }
复制代码
org.redisson.pubsub.PublishSubscribe#createListener
  1.     private RedisPubSubListener<Object> createListener(String channelName, E value) {
  2.         // 创建监听,当监听到消息回来的时候,进入onMessage进行处理
  3.         RedisPubSubListener<Object> listener = new BaseRedisPubSubListener() {
  4.             @Override
  5.             public void onMessage(CharSequence channel, Object message) {
  6.                 if (!channelName.equals(channel.toString())) {
  7.                     return;
  8.                 }
  9.                 PublishSubscribe.this.onMessage(value, (Long) message);
  10.             }
  11.         };
  12.         return listener;
  13.     }
复制代码
org.redisson.pubsub.LockPubSub#onMessage
  1.     @Override
  2.     protected void onMessage(RedissonLockEntry value, Long message) {
  3.         if (message.equals(UNLOCK_MESSAGE)) {
  4.             Runnable runnableToExecute = value.getListeners().poll();
  5.             if (runnableToExecute != null) {
  6.                 runnableToExecute.run();
  7.             }
  8.             // 释放 Semaphore
  9.             value.getLatch().release();
  10.         } else if (message.equals(READ_UNLOCK_MESSAGE)) {
  11.             while (true) {
  12.                 Runnable runnableToExecute = value.getListeners().poll();
  13.                 if (runnableToExecute == null) {
  14.                     break;
  15.                 }
  16.                 runnableToExecute.run();
  17.             }
  18.             value.getLatch().release(value.getLatch().getQueueLength());
  19.         }
  20.     }
复制代码
4、锁续期

redisson watchDog 使用时间轮技能,请参考时间轮算法分析
org.redisson.RedissonBaseLock#scheduleExpirationRenewal
  1.     protected void scheduleExpirationRenewal(long threadId) {
  2.         ExpirationEntry entry = new ExpirationEntry();
  3.         // 放入EXPIRATION_RENEWAL_MAP 这个MAP中
  4.         ExpirationEntry oldEntry = EXPIRATION_RENEWAL_MAP.putIfAbsent(getEntryName(), entry);
  5.         // 第一次进来,里面没有
  6.         if (oldEntry != null) {
  7.             // 如果其他线程来抢占这个锁,进入将线程ID保存至ExpirationEntry的threadIds这个Map中
  8.             oldEntry.addThreadId(threadId);
  9.         } else {
  10.             // 将线程ID保存至ExpirationEntry的threadIds这个Map中
  11.             entry.addThreadId(threadId);
  12.             try {
  13.                 // 执行
  14.                 renewExpiration();
  15.             } finally {
  16.                 if (Thread.currentThread().isInterrupted()) {
  17.                     cancelExpirationRenewal(threadId);
  18.                 }
  19.             }
  20.         }
  21.     }
复制代码
org.redisson.RedissonBaseLock#renewExpiration
  1.   private void renewExpiration() {
  2.         ExpirationEntry ee = EXPIRATION_RENEWAL_MAP.get(getEntryName());
  3.         if (ee == null) {
  4.             return;
  5.         }
  6.         // 开启时间轮,时间是10s之后执行我们的TimerTask任务
  7.         Timeout task = commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
  8.             @Override
  9.             public void run(Timeout timeout) throws Exception {
  10.                 // 从EXPIRATION_RENEWAL_MAP中拿到锁的对象,有可能在定时的时候被移除取消
  11.                 ExpirationEntry ent = EXPIRATION_RENEWAL_MAP.get(getEntryName());
  12.                 if (ent == null) {
  13.                     return;
  14.                 }
  15.                 Long threadId = ent.getFirstThreadId();
  16.                 if (threadId == null) {
  17.                     return;
  18.                 }
  19.                 // 给锁续期
  20.                 CompletionStage<Boolean> future = renewExpirationAsync(threadId);
  21.                 future.whenComplete((res, e) -> {
  22.                     // 异常报错,从Map移除
  23.                     if (e != null) {
  24.                         log.error("Can't update lock " + getRawName() + " expiration", e);
  25.                         EXPIRATION_RENEWAL_MAP.remove(getEntryName());
  26.                         return;
  27.                     }
  28.                     // 如果返回的是1 代表线程还占有锁,递归调用自己
  29.                     if (res) {
  30.                         // 递归再次加入时间轮
  31.                         // reschedule itself
  32.                         renewExpiration();
  33.                     } else {
  34.                         // 所不存在,这取消任务,移除相关MAP信息
  35.                         cancelExpirationRenewal(null);
  36.                     }
  37.                 });
  38.             }
  39.         }, internalLockLeaseTime / 3, TimeUnit.MILLISECONDS);
  40.         // 设置Timeout
  41.         ee.setTimeout(task);
  42.     }
复制代码
org.redisson.connection.MasterSlaveConnectionManager#newTimeout
  1.     private HashedWheelTimer timer;
  2.     @Override
  3.     public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) {
  4.         try {
  5.             // 添加进入时间轮
  6.             return timer.newTimeout(task, delay, unit);
  7.         } catch (IllegalStateException e) {
  8.             if (isShuttingDown()) {
  9.                 return DUMMY_TIMEOUT;
  10.             }
  11.             
  12.             throw e;
  13.         }
  14.     }
复制代码
  1.     protected CompletionStage<Boolean> renewExpirationAsync(long threadId) {
  2.         return evalWriteAsync(getRawName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
  3.                 "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " + // 如果当前锁存在
  4.                         "redis.call('pexpire', KEYS[1], ARGV[1]); " +  // 续期
  5.                         "return 1; " +
  6.                         "end; " +
  7.                         "return 0;",
  8.                 Collections.singletonList(getRawName()),
  9.                 internalLockLeaseTime, getLockName(threadId));
  10.     }
复制代码
5、开释锁

org.redisson.RedissonLock#unlock
  1.     @Override
  2.     public void unlock() {
  3.         try {
  4.             get(unlockAsync(Thread.currentThread().getId()));
  5.         } catch (RedisException e) {
  6.             if (e.getCause() instanceof IllegalMonitorStateException) {
  7.                 throw (IllegalMonitorStateException) e.getCause();
  8.             } else {
  9.                 throw e;
  10.             }
  11.         }
  12.     }
复制代码
org.redisson.RedissonBaseLock.unlockAsync
  1.   @Override
  2.   public RFuture<Void> unlockAsync(long threadId) {
  3.     // 进入释放锁逻辑
  4.     RFuture<Boolean> future = unlockInnerAsync(threadId);
  5.     CompletionStage<Void> f = future.handle((opStatus, e) -> {
  6.       // 移除ExpirationEntry中的threadId 并且移除 EXPIRATION_RENEWAL_MAP中的ExpirationEntry watchDog就不会继续续期  
  7.       cancelExpirationRenewal(threadId);
  8.       
  9.       // 异常处理
  10.       if (e != null) {
  11.         throw new CompletionException(e);
  12.       }
  13.       // 不存在锁信息
  14.       if (opStatus == null) {
  15.         IllegalMonitorStateException cause = new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: "
  16.                 + id + " thread-id: " + threadId);
  17.         throw new CompletionException(cause);
  18.       }
  19.       return null;
  20.     });
  21.     return new CompletableFutureWrapper<>(f);
  22.   }
复制代码
org.redisson.RedissonBaseLock.unlockInnerAsync
  1. protected RFuture<Boolean> unlockInnerAsync(long threadId) {
  2.     return evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
  3.             "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +
  4.             "return nil;" +
  5.             "end; " +
  6.             "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +
  7.             "if (counter > 0) then " +
  8.             "redis.call('pexpire', KEYS[1], ARGV[2]); " +
  9.             "return 0; " +
  10.             "else " +
  11.             "redis.call('del', KEYS[1]); " +
  12.             "redis.call('publish', KEYS[2], ARGV[1]); " +
  13.             "return 1; " +
  14.             "end; " +
  15.             "return nil;",
  16.     Arrays.asList(getName(), getChannelName()), LockPubSub.UNLOCK_MESSAGE, internalLockLeaseTime, getLockName(threadId));
  17. }
复制代码
开释锁LUA
  1. "if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then " +   # 锁已经释放
  2.             "return nil;" +
  3.             "end; " +
  4.             "local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1); " +  #重入次数减一
  5.             "if (counter > 0) then " +
  6.             "redis.call('pexpire', KEYS[1], ARGV[2]); " + # 重入次数还不为0 那说明占有锁,设置过期时间
  7.             "return 0; " +
  8.             "else " +
  9.             "redis.call('del', KEYS[1]); " +    # 重入次数为0,释放锁
  10.             "redis.call('publish', KEYS[2], ARGV[1]); " + # 发布订阅事件,唤醒其它线程,可以去竞争锁了
  11.             "return 1; " +
  12.             "end; " +
  13.             "return nil;",
复制代码
6、流程图



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表