├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── redis │ │ └── lock │ │ ├── LockApplication.java │ │ ├── annotation │ │ └── RedisLock.java │ │ ├── aop │ │ └── LockMethodAspect.java │ │ ├── config │ │ └── RedisProperties.java │ │ ├── controller │ │ └── TestController.java │ │ └── utils │ │ ├── JedisUtil.java │ │ ├── RedisLockHelper.java │ │ └── RedissonUtils.java └── resources │ └── application.properties └── test └── java └── com └── redis └── lock ├── LockApplicationTests.java └── RedisLockTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | target 4 | 5 | 6 | ### IntelliJ IDEA ### 7 | .idea 8 | *.iws 9 | *.iml 10 | *.ipr 11 | .mvn 12 | mvnw.cmd 13 | mvnw 14 | redis-distributed-lock.iml 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 前言 2 | 本篇文章主要介绍基于Redis的分布式锁实现到底是怎么一回事,其中参考了许多大佬写的文章,算是对分布式锁做一个总结 3 | 4 | ## 分布式锁概览 5 | 6 | 在多线程的环境下,为了保证一个代码块在同一时间只能由一个线程访问,Java中我们一般可以使用synchronized语法和ReetrantLock去保证,这实际上是本地锁的方式。但是现在公司都是流行分布式架构,在分布式环境下,如何保证不同节点的线程同步执行呢? 7 | 8 | 实际上,对于分布式场景,我们可以使用分布式锁,它是控制分布式系统之间**互斥访问共享资源**的一种方式。 9 | 10 | 比如说在一个分布式系统中,多台机器上部署了多个服务,当客户端一个用户发起一个数据插入请求时,如果没有分布式锁机制保证,那么那多台机器上的多个服务可能进行并发插入操作,导致数据重复插入,对于某些不允许有多余数据的业务来说,这就会造成问题。而分布式锁机制就是为了解决类似这类问题,保证多个服务之间互斥的访问共享资源,如果一个服务抢占了分布式锁,其他服务没获取到锁,就不进行后续操作。大致意思如下图所示(不一定准确): 11 | 12 | ![分布式锁](https://pjmike-1253796536.cos.ap-beijing.myqcloud.com/%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81.png) 13 | 14 | 15 | 16 | ### 分布式锁的特点 17 | 18 | 分布式锁一般有如下的特点: 19 | 20 | - 互斥性: 同一时刻只能有一个线程持有锁 21 | - 可重入性: 同一节点上的同一个线程如果获取了锁之后能够再次获取锁 22 | - 锁超时:和J.U.C中的锁一样支持锁超时,防止死锁 23 | - 高性能和高可用: 加锁和解锁需要高效,同时也需要保证高可用,防止分布式锁失效 24 | - 具备阻塞和非阻塞性:能够及时从阻塞状态中被唤醒 25 | 26 | ### 分布式锁的实现方式 27 | 我们一般实现分布式锁有以下几种方式: 28 | - 基于数据库 29 | - 基于Redis 30 | - 基于zookeeper 31 | 32 | 本篇文章主要介绍基于Redis如何实现分布式锁 33 | 34 | ## Redis的分布式锁实现 35 | 36 | ### 1. 利用setnx+expire命令 (错误的做法) 37 | 38 | Redis的SETNX命令,setnx key value,将key设置为value,当键不存在时,才能成功,若键存在,什么也不做,成功返回1,失败返回0 。 SETNX实际上就是SET IF NOT Exists的缩写 39 | 40 | 因为分布式锁还需要超时机制,所以我们利用expire命令来设置,所以利用setnx+expire命令的核心代码如下: 41 | 42 | ```java 43 | public boolean tryLock(String key,String requset,int timeout) { 44 | Long result = jedis.setnx(key, requset); 45 | // result = 1时,设置成功,否则设置失败 46 | if (result == 1L) { 47 | return jedis.expire(key, timeout) == 1L; 48 | } else { 49 | return false; 50 | } 51 | } 52 | ``` 53 | 实际上上面的步骤是有问题的,setnx和expire是分开的两步操作,不具有原子性,如果执行完第一条指令应用异常或者重启了,锁将无法过期。 54 | 55 | 一种改善方案就是使用Lua脚本来保证原子性(包含setnx和expire两条指令) 56 | 57 | ### 2. 使用Lua脚本(包含setnx和expire两条指令) 58 | 代码如下 59 | ```java 60 | public boolean tryLock_with_lua(String key, String UniqueId, int seconds) { 61 | String lua_scripts = "if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then" + 62 | "redis.call('expire',KEYS[1],ARGV[2]) return 1 else return 0 end"; 63 | List keys = new ArrayList<>(); 64 | List values = new ArrayList<>(); 65 | keys.add(key); 66 | values.add(UniqueId); 67 | values.add(String.valueOf(seconds)); 68 | Object result = jedis.eval(lua_scripts, keys, values); 69 | //判断是否成功 70 | return result.equals(1L); 71 | } 72 | ``` 73 | ### 3. 使用 set key value [EX seconds][PX milliseconds][NX|XX] 命令 (正确做法) 74 | Redis在 2.6.12 版本开始,为 SET 命令增加一系列选项: 75 | 76 | ``` 77 | SET key value[EX seconds][PX milliseconds][NX|XX] 78 | ``` 79 | - EX seconds: 设定过期时间,单位为秒 80 | - PX milliseconds: 设定过期时间,单位为毫秒 81 | - NX: 仅当key不存在时设置值 82 | - XX: 仅当key存在时设置值 83 | 84 | set命令的nx选项,就等同于setnx命令,代码过程如下: 85 | ```java 86 | public boolean tryLock_with_set(String key, String UniqueId, int seconds) { 87 | return "OK".equals(jedis.set(key, UniqueId, "NX", "EX", seconds)); 88 | } 89 | ``` 90 | value必须要具有唯一性,比如UUID,至于为什么要保证唯一性?我的理解是当我们释放锁时需要验证value值,如果value不唯一,有多个相同的值,释放锁的过程就可能会出现问题。 91 | 92 | #### 关于释放锁的问题 93 | 释放锁时需要验证value值,也就是说我们在获取锁的时候需要设置一个value,不能直接用del key这种粗暴的方式,因为直接del key任何客户端都可以进行解锁了,所以**解锁时,我们需要判断锁是否是自己的,基于value值来判断**,代码如下: 94 | 95 | ``` 96 | public boolean releaseLock_with_lua(String key,String value) { 97 | String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + 98 | "return redis.call('del',KEYS[1]) else return 0 end"; 99 | return jedis.eval(luaScript, Collections.singletonList(key), Collections.singletonList(value)).equals(1L); 100 | } 101 | ``` 102 | 这里使用Lua脚本的方式,尽量保证原子性。 103 | 104 | 105 | 使用 `set key value [EX seconds][PX milliseconds][NX|XX]` 命令 看上去很OK,实际上在Redis集群的时候也会出现问题,比如说A客户端在Redis的master节点上拿到了锁,但是这个加锁的key还没有同步到slave节点,master故障,发生故障转移,一个slave节点升级为master节点,B客户端也可以获取同个key的锁,但客户端A也已经拿到锁了,这就导致多个客户端都拿到锁。 106 | 107 | 所以针对Redis集群这种情况,还有其他方案 108 | 109 | ### 4. Redlock算法 与 Redisson 实现 110 | 111 | Redis作者 antirez基于分布式环境下提出了一种更高级的分布式锁的实现Redlock,原理如下: 112 | 113 | 114 | > 下面参考文章[Redlock:Redis分布式锁最牛逼的实现](https://mp.weixin.qq.com/s?__biz=MzU5ODUwNzY1Nw==&mid=2247484155&idx=1&sn=0c73f45f2f641ba0bf4399f57170ac9b&scene=21#wechat_redirect) 和 https://redis.io/topics/distlock 115 | 116 | 117 | 假设有5个独立的Redis节点(**注意这里的节点可以是5个Redis单master实例,也可以是5个Redis Cluster集群,但并不是有5个主节点的cluster集群**): 118 | 119 | - 获取当前Unix时间,以毫秒为单位 120 | - 依次尝试从5个实例,使用相同的key和具有唯一性的value(例如UUID)获取锁,当向Redis请求获取锁时,客户端应该设置一个网络连接和响应超时时间,这个超时时间应用小于锁的失效时间,例如你的锁自动失效时间为10s,则超时时间应该在5~50毫秒之间,这样可以避免服务器端Redis已经挂掉的情况下,客户端还在死死地等待响应结果。如果服务端没有在规定时间内响应,客户端应该尽快尝试去另外一个Redis实例请求获取锁 121 | - 客户端使用当前时间减去开始获取锁时间(步骤1记录的时间)就得到获取锁使用的时间,当且仅当从大多数(N/2+1,这里是3个节点)的Redis节点都取到锁,并且使用的时间小于锁失败时间时,锁才算获取成功。 122 | - 如果取到了锁,key的真正有效时间等于有效时间减去获取锁所使用的时间(步骤3计算的结果) 123 | - 如果某些原因,获取锁失败(没有在至少N/2+1个Redis实例取到锁或者取锁时间已经超过了有效时间),客户端应该在所有的Redis实例上进行解锁(即便某些Redis实例根本就没有加锁成功,防止某些节点获取到锁但是客户端没有得到响应而导致接下来的一段时间不能被重新获取锁) 124 | 125 | #### Redisson实现简单分布式锁 126 | 127 | 对于Java用户而言,我们经常使用Jedis,Jedis是Redis的Java客户端,除了Jedis之外,Redisson也是Java的客户端,Jedis是阻塞式I/O,而Redisson底层使用Netty可以实现非阻塞I/O,该客户端封装了锁的,继承了J.U.C的Lock接口,所以我们可以像使用ReentrantLock一样使用Redisson,具体使用过程如下。 128 | 129 | 1. 首先加入POM依赖 130 | 131 | ```xml 132 | 133 | org.redisson 134 | redisson 135 | 3.10.6 136 | 137 | ``` 138 | 2. 使用Redisson,代码如下(与使用ReentrantLock类似) 139 | 140 | 141 | ```java 142 | // 1. 配置文件 143 | Config config = new Config(); 144 | config.useSingleServer() 145 | .setAddress("redis://127.0.0.1:6379") 146 | .setPassword(RedisConfig.PASSWORD) 147 | .setDatabase(0); 148 | //2. 构造RedissonClient 149 | RedissonClient redissonClient = Redisson.create(config); 150 | 151 | //3. 设置锁定资源名称 152 | RLock lock = redissonClient.getLock("redlock"); 153 | lock.lock(); 154 | try { 155 | System.out.println("获取锁成功,实现业务逻辑"); 156 | Thread.sleep(10000); 157 | } catch (InterruptedException e) { 158 | e.printStackTrace(); 159 | } finally { 160 | lock.unlock(); 161 | } 162 | ``` 163 | 关于Redlock算法的实现,在Redisson中我们可以使用RedissonRedLock来完成,具体使用细节可以参考大佬的文章: https://mp.weixin.qq.com/s/8uhYult2h_YUHT7q7YCKYQ 164 | 165 | ## Redis实现的分布式锁轮子 166 | 167 | 下面利用SpringBoot + Jedis + AOP的组合来实现一个简易的分布式锁。 168 | 169 | 170 | 171 | ### 1. 自定义注解 172 | 自定义一个注解,被注解的方法会执行获取分布式锁的逻辑 173 | ```java 174 | @Target(ElementType.METHOD) 175 | @Retention(RetentionPolicy.RUNTIME) 176 | @Documented 177 | @Inherited 178 | public @interface RedisLock { 179 | /** 180 | * 业务键 181 | * 182 | * @return 183 | */ 184 | String key(); 185 | /** 186 | * 锁的过期秒数,默认是5秒 187 | * 188 | * @return 189 | */ 190 | int expire() default 5; 191 | 192 | /** 193 | * 尝试加锁,最多等待时间 194 | * 195 | * @return 196 | */ 197 | long waitTime() default Long.MIN_VALUE; 198 | /** 199 | * 锁的超时时间单位 200 | * 201 | * @return 202 | */ 203 | TimeUnit timeUnit() default TimeUnit.SECONDS; 204 | } 205 | ``` 206 | ### 2. AOP拦截器实现 207 | 在AOP中我们去执行获取分布式锁和释放分布式锁的逻辑,代码如下: 208 | ```java 209 | @Aspect 210 | @Component 211 | public class LockMethodAspect { 212 | @Autowired 213 | private RedisLockHelper redisLockHelper; 214 | @Autowired 215 | private JedisUtil jedisUtil; 216 | private Logger logger = LoggerFactory.getLogger(LockMethodAspect.class); 217 | 218 | @Around("@annotation(com.redis.lock.annotation.RedisLock)") 219 | public Object around(ProceedingJoinPoint joinPoint) { 220 | Jedis jedis = jedisUtil.getJedis(); 221 | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 222 | Method method = signature.getMethod(); 223 | 224 | RedisLock redisLock = method.getAnnotation(RedisLock.class); 225 | String value = UUID.randomUUID().toString(); 226 | String key = redisLock.key(); 227 | try { 228 | final boolean islock = redisLockHelper.lock(jedis,key, value, redisLock.expire(), redisLock.timeUnit()); 229 | logger.info("isLock : {}",islock); 230 | if (!islock) { 231 | logger.error("获取锁失败"); 232 | throw new RuntimeException("获取锁失败"); 233 | } 234 | try { 235 | return joinPoint.proceed(); 236 | } catch (Throwable throwable) { 237 | throw new RuntimeException("系统异常"); 238 | } 239 | } finally { 240 | logger.info("释放锁"); 241 | redisLockHelper.unlock(jedis,key, value); 242 | jedis.close(); 243 | } 244 | } 245 | } 246 | 247 | ``` 248 | ### 3. Redis实现分布式锁核心类 249 | ```java 250 | @Component 251 | public class RedisLockHelper { 252 | private long sleepTime = 100; 253 | /** 254 | * 直接使用setnx + expire方式获取分布式锁 255 | * 非原子性 256 | * 257 | * @param key 258 | * @param value 259 | * @param timeout 260 | * @return 261 | */ 262 | public boolean lock_setnx(Jedis jedis,String key, String value, int timeout) { 263 | Long result = jedis.setnx(key, value); 264 | // result = 1时,设置成功,否则设置失败 265 | if (result == 1L) { 266 | return jedis.expire(key, timeout) == 1L; 267 | } else { 268 | return false; 269 | } 270 | } 271 | 272 | /** 273 | * 使用Lua脚本,脚本中使用setnex+expire命令进行加锁操作 274 | * 275 | * @param jedis 276 | * @param key 277 | * @param UniqueId 278 | * @param seconds 279 | * @return 280 | */ 281 | public boolean Lock_with_lua(Jedis jedis,String key, String UniqueId, int seconds) { 282 | String lua_scripts = "if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then" + 283 | "redis.call('expire',KEYS[1],ARGV[2]) return 1 else return 0 end"; 284 | List keys = new ArrayList<>(); 285 | List values = new ArrayList<>(); 286 | keys.add(key); 287 | values.add(UniqueId); 288 | values.add(String.valueOf(seconds)); 289 | Object result = jedis.eval(lua_scripts, keys, values); 290 | //判断是否成功 291 | return result.equals(1L); 292 | } 293 | 294 | /** 295 | * 在Redis的2.6.12及以后中,使用 set key value [NX] [EX] 命令 296 | * 297 | * @param key 298 | * @param value 299 | * @param timeout 300 | * @return 301 | */ 302 | public boolean lock(Jedis jedis,String key, String value, int timeout, TimeUnit timeUnit) { 303 | long seconds = timeUnit.toSeconds(timeout); 304 | return "OK".equals(jedis.set(key, value, "NX", "EX", seconds)); 305 | } 306 | 307 | /** 308 | * 自定义获取锁的超时时间 309 | * 310 | * @param jedis 311 | * @param key 312 | * @param value 313 | * @param timeout 314 | * @param waitTime 315 | * @param timeUnit 316 | * @return 317 | * @throws InterruptedException 318 | */ 319 | public boolean lock_with_waitTime(Jedis jedis,String key, String value, int timeout, long waitTime,TimeUnit timeUnit) throws InterruptedException { 320 | long seconds = timeUnit.toSeconds(timeout); 321 | while (waitTime >= 0) { 322 | String result = jedis.set(key, value, "nx", "ex", seconds); 323 | if ("OK".equals(result)) { 324 | return true; 325 | } 326 | waitTime -= sleepTime; 327 | Thread.sleep(sleepTime); 328 | } 329 | return false; 330 | } 331 | /** 332 | * 错误的解锁方法—直接删除key 333 | * 334 | * @param key 335 | */ 336 | public void unlock_with_del(Jedis jedis,String key) { 337 | jedis.del(key); 338 | } 339 | 340 | /** 341 | * 使用Lua脚本进行解锁操纵,解锁的时候验证value值 342 | * 343 | * @param jedis 344 | * @param key 345 | * @param value 346 | * @return 347 | */ 348 | public boolean unlock(Jedis jedis,String key,String value) { 349 | String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + 350 | "return redis.call('del',KEYS[1]) else return 0 end"; 351 | return jedis.eval(luaScript, Collections.singletonList(key), Collections.singletonList(value)).equals(1L); 352 | } 353 | } 354 | ``` 355 | 356 | ### 4. Controller层控制 357 | 定义一个TestController来测试我们实现的分布式锁 358 | ```java 359 | @RestController 360 | public class TestController { 361 | @RedisLock(key = "redis_lock") 362 | @GetMapping("/index") 363 | public String index() { 364 | return "index"; 365 | } 366 | } 367 | ``` 368 | 369 | ## 小结 370 | 分布式锁重点在于互斥性,在任意一个时刻,只有一个客户端获取了锁。在实际的生产环境中,分布式锁的实现可能会更复杂,而我这里的讲述主要针对的是单机环境下的基于Redis的分布式锁实现,至于Redis集群环境并没有过多涉及,有兴趣的朋友可以查阅相关资料。 371 | 372 | ## 参考资料 & 鸣谢 373 | 374 | - https://mp.weixin.qq.com/s/eHsuEc8Dq3h1Kz1uqBWsjA 375 | - https://mp.weixin.qq.com/s/y2HPj2ji2KLS_eTR5nBnDA 376 | - https://mp.weixin.qq.com/s/8uhYult2h_YUHT7q7YCKYQ 377 | - https://mp.weixin.qq.com/s/xCe2ljuhMWD2rsstmNab_Q 378 | - https://crossoverjie.top/2018/03/29/distributed-lock/distributed-lock-redis/ 379 | - https://blog.battcn.com/2018/06/13/springboot/v2-cache-redislock/#%E5%85%B7%E4%BD%93%E4%BB%A3%E7%A0%81 380 | - https://redis.io/topics/distlock 381 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.1.4.RELEASE 9 | 10 | 11 | com.redis 12 | lock 13 | 0.0.1-SNAPSHOT 14 | lock 15 | Demo project for Spring Boot 16 | 17 | 18 | 1.8 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | redis.clients 32 | jedis 33 | 34 | 35 | org.redisson 36 | redisson 37 | 3.10.6 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-aop 42 | 43 | 44 | org.projectlombok 45 | lombok 46 | true 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-test 51 | test 52 | 53 | 54 | 55 | 56 | 57 | 58 | org.springframework.boot 59 | spring-boot-maven-plugin 60 | 61 | 62 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /src/main/java/com/redis/lock/LockApplication.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class LockApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(LockApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/redis/lock/annotation/RedisLock.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock.annotation; 2 | 3 | import java.lang.annotation.*; 4 | import java.util.concurrent.TimeUnit; 5 | 6 | @Target(ElementType.METHOD) 7 | @Retention(RetentionPolicy.RUNTIME) 8 | @Documented 9 | @Inherited 10 | public @interface RedisLock { 11 | /** 12 | * 业务键 13 | * 14 | * @return 15 | */ 16 | String key(); 17 | /** 18 | * 锁的过期秒数,默认是5秒 19 | * 20 | * @return 21 | */ 22 | int expire() default 5; 23 | 24 | /** 25 | * 尝试加锁,最多等待时间 26 | * 27 | * @return 28 | */ 29 | long waitTime() default Long.MIN_VALUE; 30 | /** 31 | * 锁的超时时间单位 32 | * 33 | * @return 34 | */ 35 | TimeUnit timeUnit() default TimeUnit.SECONDS; 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/redis/lock/aop/LockMethodAspect.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock.aop; 2 | 3 | import com.redis.lock.annotation.RedisLock; 4 | import com.redis.lock.utils.JedisUtil; 5 | import com.redis.lock.utils.RedisLockHelper; 6 | import lombok.extern.slf4j.Slf4j; 7 | import org.aspectj.lang.ProceedingJoinPoint; 8 | import org.aspectj.lang.annotation.Around; 9 | import org.aspectj.lang.annotation.Aspect; 10 | import org.aspectj.lang.reflect.MethodSignature; 11 | import org.slf4j.Logger; 12 | import org.slf4j.LoggerFactory; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.stereotype.Component; 15 | import redis.clients.jedis.Jedis; 16 | 17 | import java.lang.reflect.Method; 18 | import java.util.UUID; 19 | 20 | /** 21 | * @description: AOP拦截器 22 | * @author: pjmike 23 | * @create: 2019/04/24 18:43 24 | */ 25 | @Aspect 26 | @Component 27 | public class LockMethodAspect { 28 | @Autowired 29 | private RedisLockHelper redisLockHelper; 30 | @Autowired 31 | private JedisUtil jedisUtil; 32 | private Logger logger = LoggerFactory.getLogger(LockMethodAspect.class); 33 | 34 | @Around("@annotation(com.redis.lock.annotation.RedisLock)") 35 | public Object around(ProceedingJoinPoint joinPoint) { 36 | Jedis jedis = jedisUtil.getJedis(); 37 | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 38 | Method method = signature.getMethod(); 39 | 40 | RedisLock redisLock = method.getAnnotation(RedisLock.class); 41 | String value = UUID.randomUUID().toString(); 42 | String key = redisLock.key(); 43 | try { 44 | final boolean islock = redisLockHelper.lock(jedis,key, value, redisLock.expire(), redisLock.timeUnit()); 45 | logger.info("isLock : {}",islock); 46 | if (!islock) { 47 | logger.error("获取锁失败"); 48 | throw new RuntimeException("获取锁失败"); 49 | } 50 | try { 51 | return joinPoint.proceed(); 52 | } catch (Throwable throwable) { 53 | throw new RuntimeException("系统异常"); 54 | } 55 | } finally { 56 | logger.info("释放锁"); 57 | redisLockHelper.unlock(jedis,key, value); 58 | jedis.close(); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/redis/lock/config/RedisProperties.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock.config; 2 | 3 | import org.springframework.boot.context.properties.ConfigurationProperties; 4 | import org.springframework.stereotype.Component; 5 | 6 | /** 7 | * @description: 8 | * @author: pjmike 9 | * @create: 2019/04/24 19:01 10 | */ 11 | @Component 12 | @ConfigurationProperties(prefix = "redis.config") 13 | public class RedisProperties { 14 | private int max_idle; 15 | private int max_wait; 16 | private String host; 17 | private int port; 18 | private String password; 19 | private int retry_num; 20 | private int timeout; 21 | 22 | public int getMax_idle() { 23 | return max_idle; 24 | } 25 | 26 | public void setMax_idle(int max_idle) { 27 | this.max_idle = max_idle; 28 | } 29 | 30 | public int getMax_wait() { 31 | return max_wait; 32 | } 33 | 34 | public void setMax_wait(int max_wait) { 35 | this.max_wait = max_wait; 36 | } 37 | 38 | public String getHost() { 39 | return host; 40 | } 41 | 42 | public void setHost(String host) { 43 | this.host = host; 44 | } 45 | 46 | public int getPort() { 47 | return port; 48 | } 49 | 50 | public void setPort(int port) { 51 | this.port = port; 52 | } 53 | 54 | public String getPassword() { 55 | return password; 56 | } 57 | 58 | public void setPassword(String password) { 59 | this.password = password; 60 | } 61 | 62 | public int getRetry_num() { 63 | return retry_num; 64 | } 65 | 66 | public void setRetry_num(int retry_num) { 67 | this.retry_num = retry_num; 68 | } 69 | 70 | public int getTimeout() { 71 | return timeout; 72 | } 73 | 74 | public void setTimeout(int timeout) { 75 | this.timeout = timeout; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/redis/lock/controller/TestController.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock.controller; 2 | 3 | import com.redis.lock.annotation.RedisLock; 4 | import org.springframework.web.bind.annotation.GetMapping; 5 | import org.springframework.web.bind.annotation.RestController; 6 | 7 | /** 8 | * @description: 9 | * @author: pjmike 10 | * @create: 2019/04/24 21:30 11 | */ 12 | @RestController 13 | public class TestController { 14 | @RedisLock(key = "redis_lock") 15 | @GetMapping("/index") 16 | public String index() { 17 | return "index"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/redis/lock/utils/JedisUtil.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock.utils; 2 | 3 | 4 | import com.redis.lock.config.RedisProperties; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Component; 9 | import redis.clients.jedis.Jedis; 10 | import redis.clients.jedis.JedisPool; 11 | import redis.clients.jedis.JedisPoolConfig; 12 | 13 | import java.util.Map; 14 | import java.util.concurrent.ConcurrentHashMap; 15 | 16 | /** 17 | * @description: 18 | * @author: pjmike 19 | * @create: 2019/04/23 19:29 20 | */ 21 | @Component 22 | public class JedisUtil { 23 | @Autowired 24 | private RedisProperties redisProperties; 25 | private Logger logger = LoggerFactory.getLogger(JedisUtil.class); 26 | 27 | private Map map = new ConcurrentHashMap<>(); 28 | 29 | private JedisPool getPool() { 30 | String key = redisProperties.getHost() + ":" + redisProperties.getHost(); 31 | JedisPool pool; 32 | if (!map.containsKey(key)) { 33 | JedisPoolConfig config = new JedisPoolConfig(); 34 | config.setMaxIdle(redisProperties.getMax_idle()); 35 | config.setMaxWaitMillis(redisProperties.getMax_wait()); 36 | config.setTestOnBorrow(true); 37 | config.setTestOnReturn(true); 38 | 39 | pool = new JedisPool(config,redisProperties.getHost(),redisProperties.getPort(),redisProperties.getTimeout(),redisProperties.getPassword()); 40 | map.put(key, pool); 41 | } else { 42 | pool = map.get(key); 43 | } 44 | return pool; 45 | } 46 | 47 | public Jedis getJedis() { 48 | Jedis jedis = null; 49 | int count = 0; 50 | do { 51 | try { 52 | jedis = getPool().getResource(); 53 | count++; 54 | } catch (Exception e) { 55 | logger.error("get jedis failed ", e); 56 | if (jedis != null) { 57 | jedis.close(); 58 | } 59 | } 60 | } while (jedis == null && count < redisProperties.getRetry_num()); 61 | return jedis; 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/redis/lock/utils/RedisLockHelper.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock.utils; 2 | import org.springframework.stereotype.Component; 3 | import redis.clients.jedis.Jedis; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Collections; 7 | import java.util.List; 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * @description: Redis实现分布式锁 12 | * @author: pjmike 13 | * @create: 2019/04/23 19:52 14 | */ 15 | @Component 16 | public class RedisLockHelper { 17 | private long sleepTime = 100; 18 | /** 19 | * 直接使用setnx + expire方式获取分布式锁 20 | * 非原子性 21 | * 22 | * @param key 23 | * @param value 24 | * @param timeout 25 | * @return 26 | */ 27 | public boolean lock_setnx(Jedis jedis,String key, String value, int timeout) { 28 | Long result = jedis.setnx(key, value); 29 | // result = 1时,设置成功,否则设置失败 30 | if (result == 1L) { 31 | return jedis.expire(key, timeout) == 1L; 32 | } else { 33 | return false; 34 | } 35 | } 36 | 37 | /** 38 | * 使用Lua脚本,脚本中使用setnex+expire命令进行加锁操作 39 | * 40 | * @param jedis 41 | * @param key 42 | * @param UniqueId 43 | * @param seconds 44 | * @return 45 | */ 46 | public boolean Lock_with_lua(Jedis jedis,String key, String UniqueId, int seconds) { 47 | String lua_scripts = "if redis.call('setnx',KEYS[1],ARGV[1]) == 1 then" + 48 | "redis.call('expire',KEYS[1],ARGV[2]) return 1 else return 0 end"; 49 | List keys = new ArrayList<>(); 50 | List values = new ArrayList<>(); 51 | keys.add(key); 52 | values.add(UniqueId); 53 | values.add(String.valueOf(seconds)); 54 | Object result = jedis.eval(lua_scripts, keys, values); 55 | //判断是否成功 56 | return result.equals(1L); 57 | } 58 | 59 | /** 60 | * 在Redis的2.6.12及以后中,使用 set key value [NX] [EX] 命令 61 | * 62 | * @param key 63 | * @param value 64 | * @param timeout 65 | * @return 66 | */ 67 | public boolean lock(Jedis jedis,String key, String value, int timeout, TimeUnit timeUnit) { 68 | long seconds = timeUnit.toSeconds(timeout); 69 | return "OK".equals(jedis.set(key, value, "NX", "EX", seconds)); 70 | } 71 | 72 | /** 73 | * 自定义获取锁的超时时间 74 | * 75 | * @param jedis 76 | * @param key 77 | * @param value 78 | * @param timeout 79 | * @param waitTime 80 | * @param timeUnit 81 | * @return 82 | * @throws InterruptedException 83 | */ 84 | public boolean lock_with_waitTime(Jedis jedis,String key, String value, int timeout, long waitTime,TimeUnit timeUnit) throws InterruptedException { 85 | long seconds = timeUnit.toSeconds(timeout); 86 | while (waitTime >= 0) { 87 | String result = jedis.set(key, value, "nx", "ex", seconds); 88 | if ("OK".equals(result)) { 89 | return true; 90 | } 91 | waitTime -= sleepTime; 92 | Thread.sleep(sleepTime); 93 | } 94 | return false; 95 | } 96 | /** 97 | * 错误的解锁方法—直接删除key 98 | * 99 | * @param key 100 | */ 101 | public void unlock_with_del(Jedis jedis,String key) { 102 | jedis.del(key); 103 | } 104 | 105 | /** 106 | * 使用Lua脚本进行解锁操纵,解锁的时候验证value值 107 | * 108 | * @param jedis 109 | * @param key 110 | * @param value 111 | * @return 112 | */ 113 | public boolean unlock(Jedis jedis,String key,String value) { 114 | String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " + 115 | "return redis.call('del',KEYS[1]) else return 0 end"; 116 | return jedis.eval(luaScript, Collections.singletonList(key), Collections.singletonList(value)).equals(1L); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/com/redis/lock/utils/RedissonUtils.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock.utils; 2 | 3 | import org.redisson.Redisson; 4 | import org.redisson.api.RLock; 5 | import org.redisson.api.RedissonClient; 6 | import org.redisson.config.Config; 7 | 8 | import java.util.concurrent.TimeUnit; 9 | 10 | /** 11 | * @description: 12 | * @author: pjmike 13 | * @create: 2019/04/24 00:39 14 | */ 15 | public class RedissonUtils { 16 | private static void trylock() { 17 | // 1. 配置文件 18 | Config config = new Config(); 19 | config.useSingleServer() 20 | .setAddress("redis://127.0.0.1:6379") 21 | .setPassword("123456") 22 | .setDatabase(0); 23 | //2. 构造RedissonClient 24 | RedissonClient redissonClient = Redisson.create(config); 25 | 26 | //3. 设置锁定资源名称 27 | RLock lock = redissonClient.getLock("redlock"); 28 | 29 | boolean isLock; 30 | try { 31 | isLock = lock.tryLock(500, 30000, TimeUnit.MILLISECONDS); 32 | if (isLock) { 33 | //TODO 成功获取到锁 执行业务逻辑 34 | System.out.println("获取到锁,执行相应的业务逻辑"); 35 | Thread.sleep(15000); 36 | } 37 | } catch (InterruptedException e) { 38 | //TODO 39 | } finally { 40 | //解锁操作 41 | lock.unlock(); 42 | } 43 | } 44 | 45 | public static void main(String[] args) { 46 | trylock(); 47 | System.exit(0); 48 | } 49 | 50 | public static void lock() { 51 | // 1. 配置文件 52 | Config config = new Config(); 53 | config.useSingleServer() 54 | .setAddress("redis://127.0.0.1:6379") 55 | .setPassword("123456") 56 | .setDatabase(0); 57 | //2. 构造RedissonClient 58 | RedissonClient redissonClient = Redisson.create(config); 59 | 60 | //3. 设置锁定资源名称 61 | RLock lock = redissonClient.getLock("redlock"); 62 | lock.lock(); 63 | try { 64 | System.out.println("获取锁成功,实现业务逻辑"); 65 | Thread.sleep(10000); 66 | } catch (InterruptedException e) { 67 | e.printStackTrace(); 68 | } finally { 69 | lock.unlock(); 70 | } 71 | 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | redis.config.host=39.106.63.214 2 | redis.config.port=6379 3 | redis.config.password= 4 | redis.config.max_idle=30 5 | redis.config.max_wait=15000 6 | redis.config.timeout=30000 7 | redis.config.retry_num=5 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/test/java/com/redis/lock/LockApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class LockApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/com/redis/lock/RedisLockTest.java: -------------------------------------------------------------------------------- 1 | package com.redis.lock; 2 | 3 | import com.redis.lock.utils.RedisLockHelper; 4 | import org.junit.Before; 5 | import org.springframework.util.StopWatch; 6 | import redis.clients.jedis.Jedis; 7 | import redis.clients.jedis.JedisPool; 8 | import redis.clients.jedis.JedisPoolConfig; 9 | 10 | import java.util.concurrent.ExecutorService; 11 | import java.util.concurrent.Executors; 12 | import java.util.concurrent.TimeUnit; 13 | 14 | /** 15 | * @description: 16 | * @author: 13572 17 | * @create: 2019/04/24 22:54 18 | */ 19 | public class RedisLockTest { 20 | private ExecutorService executorService = Executors.newFixedThreadPool(200); 21 | private JedisPool jedisPool; 22 | private RedisLockTest() { 23 | JedisPoolConfig config = new JedisPoolConfig(); 24 | config.setMaxTotal(60); 25 | config.setMaxIdle(60); 26 | config.setTestOnReturn(true); 27 | config.setTestOnBorrow(true); 28 | String password = "123456"; 29 | jedisPool = new JedisPool(config, "39.106.63.214", 6379, 10000, password); 30 | } 31 | 32 | public static void main(String[] args) throws InterruptedException { 33 | RedisLockTest redisLockTest = new RedisLockTest(); 34 | RedisLockHelper redisLockHelper = new RedisLockHelper(); 35 | for (int i = 0; i < 200; i++) { 36 | redisLockTest.executorService.execute(()->{ 37 | try (Jedis jedis = redisLockTest.jedisPool.getResource()){ 38 | redisLockHelper.lock(jedis, "pjmike", "1", 20, TimeUnit.SECONDS); 39 | System.out.println("加锁成功"); 40 | redisLockHelper.unlock(jedis, "pjmike", "1"); 41 | } 42 | }); 43 | } 44 | redisLockTest.executorService.awaitTermination(1, TimeUnit.SECONDS); 45 | redisLockTest.executorService.shutdown(); 46 | } 47 | 48 | } 49 | --------------------------------------------------------------------------------