展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > Redis分布式锁实现的方法是什么

Redis分布式锁实现的方法是什么

Redis Assistant
Redis Assistant

Redis Assistant 是一款为Redis设计的高效可视化管理与监控工具,提供多种操作模式,高效处理服务器数据。日常使用里的持续防护和信息管理会更突出,适合把安全控制放进长期使用流程中的场景。

¥19
Windows/macOS/Linux 2026-08-22
正版软件 Windows macOS软件 Linux 数据库管理工具
立即下载

一、分布式锁是什么分布式锁是满足分布式系统或集群模式下多进程可见并且互斥的锁。基于Redis实现分布式锁:1、获取锁互斥:确保只能有一个线程获取锁;非阻塞:尝试获取锁,成功返回true,失败返回false;添加锁过期时间,避免服务宕机引起死锁。SETlockthread1NXEX102、释放锁手动释放;DELkey1超时释放,获取锁时添加一个超时锁;二、代码实例packagecom.guor.utils;importorg.springframework.data.redis.core.StringRed

本文目录

      一、分布式锁是什么

      分布式锁是 满足分布式系统或集群模式下多进程可见并且互斥的锁。

      基于Redis实现分布式锁:

      1、获取锁

      • 互斥:确保只能有一个线程获取锁;

      • 非阻塞:尝试获取锁,成功返回true,失败返回false;

      添加锁过期时间,避免服务宕机引起死锁。

      SET lock thread1 NX EX 10

      2、释放锁

      • 手动释放;DEL key1

      • 超时释放,获取锁时添加一个超时锁;

      二、代码实例

      package com.guor.utils;
      
      import org.springframework.data.redis.core.StringRedisTemplate;
      
      import java.util.concurrent.TimeUnit;
      
      public class RedisLock implements ILock{
      
          private String name;
          private StringRedisTemplate stringRedisTemplate;
      
          public RedisLock(String name, StringRedisTemplate stringRedisTemplate) {
              this.name = name;
              this.stringRedisTemplate = stringRedisTemplate;
          }
      
          private static final String KEY_PREFIX = "lock:";
      
          @Override
          public boolean tryLock(long timeout) {
              // 获取线程唯一标识
              long threadId = Thread.currentThread().getId();
              // 获取锁
              Boolean success = stringRedisTemplate.opsForValue()
                      .setIfAbsent(KEY_PREFIX + name, threadId+"", timeout, TimeUnit.SECONDS);
              // 防止拆箱的空指针异常
              return Boolean.TRUE.equals(success);
          }
      
          @Override
          public void unlock() {
              stringRedisTemplate.delete(KEY_PREFIX + name);
          }
      }

      上面代码存在锁误删问题:

      1. 如果线程1获取锁,但线程1发生了阻塞,导致Redis超时释放锁;

      2. 此时,线程2尝试获取锁,成功,并执行业务;

      3. 此时,线程1重新开始执行任务,并执行完毕,执行释放锁(即删除锁);

      4. 但是,线程1删除的锁,和线程2的锁是同一把锁,这就是分布式锁误删问题;

      在释放锁时,释放线程自己的分布式锁,就可以解决这个问题。

      package com.guor.utils;
      
      import cn.hutool.core.lang.UUID;
      import org.springframework.data.redis.core.StringRedisTemplate;
      
      import java.util.concurrent.TimeUnit;
      
      public class RedisLock implements ILock{
      
          private String name;
          private StringRedisTemplate stringRedisTemplate;
      
          public RedisLock(String name, StringRedisTemplate stringRedisTemplate) {
              this.name = name;
              this.stringRedisTemplate = stringRedisTemplate;
          }
      
          private static final String KEY_PREFIX = "lock:";
          private static final String UUID_PREFIX = UUID.randomUUID().toString(true) + "-";
      
          @Override
          public boolean tryLock(long timeout) {
              // 获取线程唯一标识
              String threadId = UUID_PREFIX + Thread.currentThread().getId();
              // 获取锁
              Boolean success = stringRedisTemplate.opsForValue()
                      .setIfAbsent(KEY_PREFIX + name, threadId, timeout, TimeUnit.SECONDS);
              // 防止拆箱的空指针异常
              return Boolean.TRUE.equals(success);
          }
      
          @Override
          public void unlock() {
              // 获取线程唯一标识
              String threadId = UUID_PREFIX + Thread.currentThread().getId();
              // 获取锁中的标识
              String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
              // 判断标示是否一致
              if(threadId.equals(id)) {
                  // 释放锁
                  stringRedisTemplate.delete(KEY_PREFIX + name);
              }
          }
      }

      三、基于SETNX实现的分布式锁存在下面几个问题

      1、不可重入

      同一个线程无法多次获取同一把锁。

      2、不可重试

      获取锁只尝试一次就返回false,没有重试机制。

      3、超时释放

      锁的超时释放虽然可以避免死锁,但如果业务执行耗时较长,也会导致锁释放,存在安全隐患。

      4、主从一致性

      如果Redis是集群部署的,主从同步存在延迟,当主机宕机时,此时会选一个从作为主机,但是此时的从没有锁标识,此时,其它线程可能会获取到锁,导致安全问题。

      四、Redisson实现分布式锁

      Redisson是一个在Redis的基础上实现的Java驻内存数据网格。它不仅提供了一系列的分布式的Java常用对象,还提供了许多分布式服务,其中包含各种分布式锁的实现。

      1、pom

      
      
          org.redisson
          redisson
          3.13.6
      

      2、配置类

      package com.guor.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();
      
              /**
               * 单点地址useSingleServer,集群地址useClusterServers
               */
              config.useSingleServer().setAddress("redis://127.0.0.1:6379").setPassword("123456");
              // 创建RedissonClient对象
              return Redisson.create(config);
          }
      }

      3、测试类

      package com.guor;
      
      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 {
      
          @Resource
          private RedissonClient redissonClient;
      
          private RLock lock;
      
          @BeforeEach
          void setUp() {
          	// 获取指定名称的锁
              lock = redissonClient.getLock("nezha");
          }
      
          @Test
          void test() throws InterruptedException {
              // 尝试获取锁
              boolean isLock = lock.tryLock(1L, TimeUnit.SECONDS);
              if (!isLock) {
                  log.error("获取锁失败");
                  return;
              }
              try {
                  log.info("哪吒最帅,哈哈哈");
              } finally {
                  // 释放锁
                  lock.unlock();
              }
          }
      }

      五、探索tryLock源码

      1、tryLock源码

      尝试获取锁
      public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
      	// 最大等待时间
      	long time = unit.toMillis(waitTime);
      	long current = System.currentTimeMillis();
      	long threadId = Thread.currentThread().getId();
      	Long ttl = this.tryAcquire(waitTime, leaseTime, unit, threadId);
      	if (ttl == null) {
      		return true;
      	} else {
      		// 剩余等待时间 = 最大等待时间 - 获取锁失败消耗的时间
      		time -= System.currentTimeMillis() - current;
      		if (time <= 0L) {// 获取锁失败
      			this.acquireFailed(waitTime, unit, threadId);
      			return false;
      		} else {
      			// 再次尝试获取锁
      			current = System.currentTimeMillis();
      			// subscribe订阅其它释放锁的信号
      			RFuture subscribeFuture = this.subscribe(threadId);
      			// 当Future在等待指定时间time内完成时,返回true
      			if (!subscribeFuture.await(time, TimeUnit.MILLISECONDS)) {
      				if (!subscribeFuture.cancel(false)) {
      					subscribeFuture.onComplete((res, e) -> {
      						if (e == null) {
      							// 取消订阅
      							this.unsubscribe(subscribeFuture, threadId);
      						}
      
      					});
      				}
      
      				this.acquireFailed(waitTime, unit, threadId);
      				return false;// 获取锁失败
      			} else {
      				try {
      					// 剩余等待时间 = 剩余等待时间 - 获取锁失败消耗的时间
      					time -= System.currentTimeMillis() - current;
      					if (time <= 0L) {
      						this.acquireFailed(waitTime, unit, threadId);
      						boolean var20 = false;
      						return var20;
      					} else {
      						boolean var16;
      						do {
      							long currentTime = System.currentTimeMillis();
      							// 重试获取锁
      							ttl = this.tryAcquire(waitTime, leaseTime, unit, threadId);
      							if (ttl == null) {
      								var16 = true;
      								return var16;
      							}
      							// 再次失败了,再看一下剩余时间
      							time -= System.currentTimeMillis() - currentTime;
      							if (time <= 0L) {
      								this.acquireFailed(waitTime, unit, threadId);
      								var16 = false;
      								return var16;
      							}
      							// 再重试获取锁
      							currentTime = System.currentTimeMillis();
      							if (ttl >= 0L && ttl < time) {
      								// 通过信号量的方式尝试获取信号,如果等待时间内,依然没有结果,会返回false
      								((RedissonLockEntry)subscribeFuture.getNow()).getLatch().tryAcquire(ttl, TimeUnit.MILLISECONDS);
      							} else {
      								((RedissonLockEntry)subscribeFuture.getNow()).getLatch().tryAcquire(time, TimeUnit.MILLISECONDS);
      							}
      							time -= System.currentTimeMillis() - currentTime;
      						} while(time > 0L);
      
      						this.acquireFailed(waitTime, unit, threadId);
      						var16 = false;
      						return var16;
      					}
      				} finally {
      					this.unsubscribe(subscribeFuture, threadId);
      				}
      			}
      		}
      	}
      }

      2、重置锁的有效期

      private void scheduleExpirationRenewal(long threadId) {
      	RedissonLock.ExpirationEntry entry = new RedissonLock.ExpirationEntry();
      	// this.getEntryName():锁的名字,一个锁对应一个entry
      	// putIfAbsent:如果不存在,将锁和entry放到map里
      	RedissonLock.ExpirationEntry oldEntry = (RedissonLock.ExpirationEntry)EXPIRATION_RENEWAL_MAP.putIfAbsent(this.getEntryName(), entry);
      	if (oldEntry != null) {
      		// 同一个线程多次获取锁,相当于重入
      		oldEntry.addThreadId(threadId);
      	} else {
      		// 如果是第一次
      		entry.addThreadId(threadId);
      		// 更新有效期
      		this.renewExpiration();
      	}
      }

      更新有效期,递归调用更新有效期,永不过期

      private void renewExpiration() {
      	// 从map中得到当前锁的entry
      	RedissonLock.ExpirationEntry ee = (RedissonLock.ExpirationEntry)EXPIRATION_RENEWAL_MAP.get(this.getEntryName());
      	if (ee != null) {
      		// 开启延时任务
      		Timeout task = this.commandExecutor.getConnectionManager().newTimeout(new TimerTask() {
      			public void run(Timeout timeout) throws Exception {
      				RedissonLock.ExpirationEntry ent = (RedissonLock.ExpirationEntry)RedissonLock.EXPIRATION_RENEWAL_MAP.get(RedissonLock.this.getEntryName());
      				if (ent != null) {
      					// 取出线程id
      					Long threadId = ent.getFirstThreadId();
      					if (threadId != null) {
      						// 刷新有效期
      						RFuture future = RedissonLock.this.renewExpirationAsync(threadId);
      						future.onComplete((res, e) -> {
      							if (e != null) {
      								RedissonLock.log.error("Can't update lock " + RedissonLock.this.getName() + " expiration", e);
      							} else {
      								if (res) {
      									// 递归调用更新有效期,永不过期
      									RedissonLock.this.renewExpiration();
      								}
      							}
      						});
      					}
      				}
      			}
      		}, this.internalLockLeaseTime / 3L, TimeUnit.MILLISECONDS);// 10S
      		ee.setTimeout(task);
      	}
      }
      更新有效期
      protected RFuture renewExpirationAsync(long threadId) {
      	return this.evalWriteAsync(this.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(this.getName()), this.internalLockLeaseTime, this.getLockName(threadId));
      }

      3、调用lua脚本

       RFuture tryLockInnerAsync(long waitTime, long leaseTime, TimeUnit unit, long threadId, RedisStrictCommand command) {
      	// 锁释放时间
      	this.internalLockLeaseTime = unit.toMillis(leaseTime);
      	return this.evalWriteAsync(this.getName(), LongCodec.INSTANCE, command, 
      		// 判断锁成功
      		"if (redis.call('exists', KEYS[1]) == 0) then
      			redis.call('hincrby', KEYS[1], ARGV[2], 1); // 如果不存在,记录锁标识,次数+1
      			redis.call('pexpire', KEYS[1], ARGV[1]); // 设置锁有效期
      			return nil; // 相当于Java的null
      		end; 
      		if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then 
      			redis.call('hincrby', KEYS[1], ARGV[2], 1); // 如果存在,判断锁标识是否是自己的,次数+1
      			redis.call('pexpire', KEYS[1], ARGV[1]); // 设置锁有效期
      			return nil; 
      		end; 
      		// 判断锁失败,pttl:指定锁剩余有效期,单位毫秒,KEYS[1]:锁的名称
      		return redis.call('pttl', KEYS[1]);", 
      			Collections.singletonList(this.getName()), this.internalLockLeaseTime, this.getLockName(threadId));
      }

      六、释放锁unlock源码

      1、取消更新任务

      public RFuture unlockAsync(long threadId) {
      	RPromise result = new RedissonPromise();
      	RFuture future = this.unlockInnerAsync(threadId);
      	future.onComplete((opStatus, e) -> {
      		// 取消更新任务
      		this.cancelExpirationRenewal(threadId);
      		if (e != null) {
      			result.tryFailure(e);
      		} else if (opStatus == null) {
      			IllegalMonitorStateException cause = new IllegalMonitorStateException("attempt to unlock lock, not locked by current thread by node id: " + this.id + " thread-id: " + threadId);
      			result.tryFailure(cause);
      		} else {
      			result.trySuccess((Object)null);
      		}
      	});
      	return result;
      }

      2、删除定时任务

      void cancelExpirationRenewal(Long threadId) {
      	// 从map中取出当前锁的定时任务entry
      	RedissonLock.ExpirationEntry task = (RedissonLock.ExpirationEntry)EXPIRATION_RENEWAL_MAP.get(this.getEntryName());
      	if (task != null) {
      		if (threadId != null) {
      			task.removeThreadId(threadId);
      		}
      		// 删除定时任务
      		if (threadId == null || task.hasNoThreads()) {
      			Timeout timeout = task.getTimeout();
      			if (timeout != null) {
      				timeout.cancel();
      			}
      
      			EXPIRATION_RENEWAL_MAP.remove(this.getEntryName());
      		}
      	}
      }
      本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
      作者最新文章
      编程开发
      相关文章 更多
      精品专题 更多
      装机必备

      正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

      Windows

      正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

      PDF教程

      正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

      macOS软件

      正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

      IOS软件

      正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

      AI

      正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

      Mac软件 更多
      Ollama
      Ollama

      Ollama 可在自己的电脑上下载和运行语言模型,并通过聊天界面、命令行或本地 API 使用。支持 macOS、Windows 与 Linux,模型大小、内存和上下文设置会影响运行体验,也提供独立的云模型入口。

      GitHub Desktop
      GitHub Desktop

      GitHub Desktop 把 Git 仓库的改动对比、提交、分支切换和同步放进桌面窗口,适合不想频繁输入命令的开发者。支持 Windows 与 macOS,可连接 GitHub 仓库并配合编辑器完成日常协作。

      Antinote
      Antinote

      Antinote 是 Mac 上的轻量草稿板,支持快捷唤出、清单、计算、单位换算和图片文字识别,也能把内容转到其他笔记工具。要求 macOS 14 以上,适合临时记事和桌面工作中的快速整理。

      Unfold
      Unfold

      Unfold 为 Finder 的快速查看补充压缩包目录、Markdown、文件夹大小及更多媒体格式预览。需要 macOS 15.6 或更新系统,安装并启用 Quick Look 扩展后,选中文件按空格即可使用。

      TCP Viewer
      TCP Viewer

      TCP Viewer 在原生 Mac 界面中提供实时抓包、协议字段、十六进制数据和 TCP/UDP 流查看,也可打开 PCAP 文件。面向 Apple Silicon 与 macOS 15 以上系统,适合定位应用连接和网络通信问题。

      Notomo
      Notomo

      Notomo 在 macOS 上为 Apple Notes 补充 Markdown 输入、命令面板、快捷打开、模板与 AI 辅助。笔记仍保存在苹果备忘录中;需要 macOS 15 或更新系统,AI 服务使用自己的供应商配置。

      FluxDown
      FluxDown

      FluxDown 将普通链接、磁力与种子等下载任务放进同一窗口,支持分段下载、续传和队列管理。可在 Windows、macOS、Linux 桌面使用,也提供适合 NAS 与服务器的无界面方案。

      汽水音乐
      汽水音乐

      汽水音乐提供个性化推荐、场景电台及抖音音乐收藏衔接,适合发现歌曲和管理日常听歌内容。这里说明播放、一起听及多平台入口,并提醒区分曲目版权与会员权益。

      LibreOffice 桌面版
      LibreOffice 桌面版

      LibreOffice桌面版提供Writer、Calc、Impress等办公组件,可本地处理文档并交换Office格式。了解实际功能、商用许可、兼容性检查和企业支持的区别。

      Numbers macOS版
      Numbers macOS版

      Numbers macOS版用于预算、数据整理和可视化报告,支持公式、图表、数据透视表及iCloud协作。了解Excel文件交换、Mac安装条件和多端使用差异。

      Qoder
      Qoder

      Qoder智能体工作台将编程任务、项目知识整理和自动化集中处理。本页介绍任务执行、Repo Wiki与结果审阅,区分Qoder IDE、系统安装选项和账户套餐,并提供官方下载入口。

      AI
      讯飞智作 网页版
      讯飞智作 网页版

      讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

      WINDOWS 更多
      Ollama
      Ollama

      Ollama 可在自己的电脑上下载和运行语言模型,并通过聊天界面、命令行或本地 API 使用。支持 macOS、Windows 与 Linux,模型大小、内存和上下文设置会影响运行体验,也提供独立的云模型入口。

      GitHub Desktop
      GitHub Desktop

      GitHub Desktop 把 Git 仓库的改动对比、提交、分支切换和同步放进桌面窗口,适合不想频繁输入命令的开发者。支持 Windows 与 macOS,可连接 GitHub 仓库并配合编辑器完成日常协作。

      Golden 8
      Golden 8

      Golden 8 是 Benthic Software 的 Windows Oracle 数据库客户端,提供多标签 SQL 编辑、关联查询辅助、结果表格与导出。连接前需要安装与软件位数一致的 Oracle Client,可先使用 30 天试用版。

      FluxDown
      FluxDown

      FluxDown 将普通链接、磁力与种子等下载任务放进同一窗口,支持分段下载、续传和队列管理。可在 Windows、macOS、Linux 桌面使用,也提供适合 NAS 与服务器的无界面方案。

      汽水音乐
      汽水音乐

      汽水音乐提供个性化推荐、场景电台及抖音音乐收藏衔接,适合发现歌曲和管理日常听歌内容。这里说明播放、一起听及多平台入口,并提醒区分曲目版权与会员权益。

      微信 Windows版
      微信 Windows版

      微信Windows版适合电脑聊天、会话查找和文件传送。本页说明登录与文件管理、电脑办公优势,以及大文件失败、版本差异和本地记录的核对方法。

      LibreOffice 桌面版
      LibreOffice 桌面版

      LibreOffice桌面版提供Writer、Calc、Impress等办公组件,可本地处理文档并交换Office格式。了解实际功能、商用许可、兼容性检查和企业支持的区别。

      Qoder
      Qoder

      Qoder智能体工作台将编程任务、项目知识整理和自动化集中处理。本页介绍任务执行、Repo Wiki与结果审阅,区分Qoder IDE、系统安装选项和账户套餐,并提供官方下载入口。

      AI
      讯飞智作 网页版
      讯飞智作 网页版

      讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

      火山引擎 网页版
      火山引擎 网页版

      火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

      PixTV 网页版
      PixTV 网页版

      PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。

      讯飞绘文 网页版
      讯飞绘文 网页版

      讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

      即将离开本站
      您即将前往第三方网站,请确认是否继续?